Connect to MySQL database using MySQLConnectorNet
1. First download and install Connector/Net, http://www.mysql.com/downloads/connector/net/
And get the required dynamic link library MySql.Data.dll from the installation directory. If you already have MySql.Data.dll, you can also not install it.
2. Add a reference to the dynamic link library in the project
3. Create some test data in mySQL such as:
I'm using phpAdmin
INSERT INTO stuinfo( first_name, last_name, Birthdate ) VALUES ( 'John', 'Smith', '1990-2-3' )
static void Main(string[] args) { string url = "server=127.0.0.1;user=root;database=student;port=3306;password=root;";//Indicate the database address, username, database name, port, password to connect to MySqlConnection conn = new MySqlConnection(url);//Instantiate the connection conn.Open();//Open the connection string sta = "select * from stuinfo";//Execute a simple statement MySqlCommand = new MySqlCommand(sta, conn); MySqlDataReader reader = comm.ExecuteReader();//Receive the execution result with MySqlDataReader while (reader.Read()) { Console.WriteLine(reader.GetString(0) + " " + reader.GetString(1) + " " + reader.GetString(2) + " " + reader.GetString(3));//Read the result of the query} Console.ReadKey(); reader.Close(); conn.Close();//Close the connection} Connecting to MySQL database using MySQLDriverCS
It is similar to using MySQLConnectorNet. First, download and install MySQLDriverCS and get the dynamic link library file:
http://sourceforge.net/projects/mysqldrivercs/
Add MySQLDriverCS.dll to the project's reference:
Or use the test data that has been established in the MySQL database, so I directly write C# code:
static void Main(string[] args) { MySQLConnection conn = new MySQLConnection(new MySQLConnectionString("127.0.0.1","student", "root", "root", "3306).AsString); conn.Open(); MySQLCommand cmd = new MySQLCommand("select * from stuinfo", conn); DbDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader.GetString(0) + " " + reader.GetString(1) + " " + reader.GetString(2) + " " + reader.GetString(3));//Read the result of the query} Console.ReadKey(); reader.Close(); conn.Close();//Close the connection} Execution results:
The data was read out successfully.