Method 1: use the official MySQL component
Use the MySQL Connector/Net Component released by MySQL, which is a. NET dedicated access component designed by MySQL for ADO. NET to access the MySQL database. After the component is completed, you must reference the component in the project. You can also add the following nodes to the <assemblies> node in the configuration file:
Copy codeThe Code is as follows: <add assembly = "MySql. Data, Version = 5.1.5.0, Culture = neutral, PublicKeyToken = C5687FC88969C44D"/>
Then, reference the namespace MySql. Data. MySqlClient in the program to connect to the MySQL database. For example:
Copy codeThe Code is as follows: protected void MySqlCon ()
{
// The database connection string is no different from the SQL SERVER connection string
String constr = "server = localhost; User Id = root; password = root; Database = test ";
// Use the dedicated object provided by MySql Connector/net below
MySqlConnection mycon = new MySqlConnection (constr );
Mycon. Open ();
MySqlCommand mycmd = new MySqlCommand ("select * from users", mycon );
MySqlDataReader myreader = mycmd. ExecuteReader ();
While (myreader. Read ())
{
If (myreader. HasRows)
{
Response. Write (myreader. GetString ("email") + "<br/> ");
}
}
Myreader. Close ();
Mycon. Close ();
}
Method 2: Use ODBC. NET
Generally, the ODBC. NET DataProvider is part of the standard. NET Framework (Version 1.1 and later), so it will be automatically installed with the latter. Once ODBC. NET is installed, You need to download the ODBC driver for MySQL: MySQL Connector/ODBC. The latest version is 3.51. After installation, You Can Use ODBC. NET to connect to the MySQL database. First, you need to introduce the System. Data. Odbc namespace in the program. The specific example is as follows:
Copy codeThe Code is as follows: public void Connect_Odbc ()
{
// Create a MySQL odbc dsn in advance.
String odbcString = "DSN = MySQL ;";
// String odbcString = "DRIVER = {mysqlodbc 3.51 Driver};" +
// "SERVER = localhost;" +
// "Port = 3306;" + // This setting can be omitted when you connect to the local database
// "DATABASE = test;" +
// "UID = root;" +
// "PASSWORD = root;" +
// "OPTION = 3 ";
OdbcConnection odbcConn = new OdbcConnection (odbcString );
OdbcConn. Open ();
OdbcCommand odbcCmd = new OdbcCommand ("SELECT * FROM users", odbcConn );
OdbcDataReader myreader = odbcCmd. ExecuteReader ();
While (myreader. Read ())
{
If (myreader. HasRows)
{
Response. Write (myreader. GetString (0) + "<br/> ");
}
}
Myreader. Close ();
OdbcConn. Close ();
}