Using mysqlconnectornet to connect to the MySQL database
1. First Download and install connector/net,http://www.mysql.com/downloads/connector/net/
and from the installation directory to get the required dynamic link library MySql.Data.dll, if there is already MySql.Data.dll also can not install.
2. Add a reference to the dynamic-link library in your project
3. Build some test data in MySQL such as:
I was 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; ";/ /Specify the database address to connect to, username, database name, port, password
mysqlconnection conn = new mysqlconnection (URL);//Instantiate Connection
Conn. Open ();//Opening connection
string sta = "SELECT * from Stuinfo";/execute a simple statement
Mysqlcommand comm = new Mysqlcommand (STA, conn);
mysqldatareader reader = Comm. ExecuteReader ()///Mysqldatareader Receive execution result while
reader. Read ())
{
Console.WriteLine (reader). GetString (0) + "" + Reader. GetString (1) + "" + Reader. GetString (2) + "" + Reader. GetString (3))//read out the results of the query
}
console.readkey ();
Reader. Close ();
Conn. Close ();//Turn off connection
}
Using Mysqldrivercs to connect to the MySQL database
similar to the use of mysqlconnectornet, first download the installation Mysqldrivercs after the dynamic link library file:
http://sourceforge.net/projects/mysqldrivercs/
Add MySQLDriverCS.dll to the project's reference:
or use it to buy the test data that has been established in the MySQL database, so write C # code directly:
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 out the results of the query
}
console.readkey ();
Reader. Close ();
Conn. Close ();//Turn off connection
}
Execution results:
The data was read out successfully.