C # Use ODBC to connect to the MySQL database
1. ODBC. Net (ODBC. NET data provider) is a free. NET Framework additional component, which needs to be downloaded from the Microsoft website.
2.7 or later.
2, also need to install MySQL ODBC driver, for: http://www.mysql.com/downloads/connector/odbc/
3. You also need to configure the DSN in "ODBC data source Manager", as shown in the steps:
(1) Open the ODBC configuration interface
(2) Click "add" and select MySql driver
(3) After the attack is completed, the database connection attribute must be configured.
Data Source Name: name of the data source (used in the Program)
Description: description, which is optional.
TCP/IP server: Database IP address, Port: Port
User: the username used to log on to the database.
Password: Password
Database: name of the database to be operated
---------------------------------------------------------------------------------
After entering the information, click the "test" button in the lower-right corner to test whether the database can be connected, for example:
The link is successfully linked.
(4) After the configuration is complete, you can view the configured Mysql Data Source in the ODBC data source.
(5) The ODBC data source configuration is complete.
Operate C # Database code:
Program. CS
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data.Odbc;namespace AccessDB{ class Program { static void Main(string[] args) { string constr = "DSN=MySQL;" + "UID=root;" + "PWD=671354;"; OdbcConnection conn = new OdbcConnection(constr); conn.Open(); //string insert = "insert into test.test values(null, 'wwh', '123')"; //string select = "select * from test.test"; //string update = "update test.test set name='whwang' where id = 11"; string delete = "delete from test.test where id = 12"; DB db = new DB(); //db.Insert(conn, insert); //db.Select(conn, select); //db.Update(conn, update); db.Delete(conn, delete); conn.Close(); Console.Read(); } }}
DB. CS
using System;using System.Collections.Generic;using System.ComponentModel;using System.Text;using System.Data.Odbc;namespace AccessDB{ class DB { public void Select(OdbcConnection conn, string selectSql) { OdbcCommand cmd = new OdbcCommand(selectSql, conn); OdbcDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.Write(reader.GetString(0) + ", "); Console.Write(reader.GetString(1) + ", "); Console.WriteLine(reader.GetString(2)); } } public void Insert(OdbcConnection conn, string insertSql) { OdbcCommand cmd = new OdbcCommand(insertSql, conn); cmd.ExecuteNonQuery(); cmd.Dispose(); } public void Update(OdbcConnection conn, string updateSql) { OdbcCommand cmd = new OdbcCommand(updateSql, conn); cmd.ExecuteNonQuery(); cmd.Dispose(); } public void Delete(OdbcConnection conn, string deleteSql) { OdbcCommand cmd = new OdbcCommand(deleteSql, conn); cmd.ExecuteNonQuery(); cmd.Dispose(); } }}