There are two ways in which we can connect MySQL database, first look at the direct-linked way:
Method One:
Use MySQL Launch of MySQL connector/net components, the component is MySQL to be ADO Access MySQL of database design . NET Private Access Components. After you complete the component, you need to reference this component in your project .
then reference the namespace in the program MySql.Data.MySqlClient , you can start the connection MySQL database operation, examples are as follows:
1protected void Mysqlcon ()
2{
3// database connection string followed by connection SQL SERVER no difference .
4 string constr = "server=localhost; User Id=root;password=root;database=test ";
5
6// Use the following MYSQL connector/net dedicated objects provided
7 Mysqlconnection mycon = new Mysqlconnection (CONSTR);
8 Mycon. Open ();
9 Mysqlcommand mycmd = new Mysqlcommand ("SELECT * from users", mycon);
Ten Mysqldatareader myreader = myCMD. ExecuteReader ();
One while (myreader. Read ())
12 {
if (myreader. HasRows)
14 {
MessageBox.Show (myreader. GetString ("email"));
16}
17}
myreader. Close ();
Mycon. Close ();
20
21}
The second way is the way the bridge is linked:
Use odbc.net . In general,odbc.net 's dataprovider is the standard . NET Framework (1.1 and above), so it will be installed automatically with the latter. Once you have confirmed that the odbc.net installation is complete, you will need to download the ODBC driver for MySQL : MySQL connector/odbc, Currently the latest version is 3.51. After installation, you can use odbc.net to connect to MySQL database, first need to introduce in the program SYSTEM.DATA.ODBC namespaces, the following are examples:
1 public void Connect_odbc ()
2 {
3// need to be created beforehand MySQL ODBC DSN.
4 string odbcstring = "dsn=mysql;";
5
6//string odbcstring = "Driver={mysql ODBC 3.51 DRIVER};" +
7//"SERVER=LOCALHOST;" +
8//"port=3306;" +/ / This setting can be omitted when connecting to a local database
9//"database=test;" +
+//"uid=root;" +
One//"password=root;" +
//"option=3";
13
OdbcConnection odbcconn = new OdbcConnection (odbcstring);
Odbcconn.open ();
OdbcCommand odbccmd = New OdbcCommand ("SELECT * from users", Odbcconn);
OdbcDataReader myreader = Odbccmd.executereader ();
while (myreader. Read ())
19 {
if (myreader. HasRows)
21 {
MessageBox.Show (myreader. GetString (0)) 003B
23}
24}
myreader. Close ();
Odbcconn.close ();
27}
From the above example, we can see that the method of connection and we have previously learned the same as the ADO is SqlConnection, is now Mysqlconnection, formerly SqlCommand, is now Mysqlcommand, So the method used is very similar!