使用MySQLConnectorNet連接MySQL數據庫
1.首先下載安裝Connector/Net,http://www.mysql.com/downloads/connector/net/
并從安裝目錄中得到所需動態鏈接庫MySql.Data.dll,如果已經有MySql.Data.dll也可以不用安裝。
2.在項目中添加對該動態鏈接庫的引用
3.在mySQL中建一些測試數據如:
我是使用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;";//指明要連接的數據庫地址,用戶名,數據庫名,端口,密碼 MySqlConnection conn = new MySqlConnection(url);//實例化連接 conn.Open();//打開連接 string sta = "select * from stuinfo";//執行一個簡單的語句 MySqlCommand comm = new MySqlCommand(sta, conn); MySqlDataReader reader = comm.ExecuteReader();//用MySqlDataReader接收執行結果 while (reader.Read()) { Console.WriteLine(reader.GetString(0) + " " + reader.GetString(1) + " " + reader.GetString(2) +" " + reader.GetString(3));//讀出查詢的結果 } Console.ReadKey(); reader.Close(); conn.Close();//關閉連接 }
使用MySQLDriverCS連接MySQL數據庫
與使用MySQLConnectorNet大同小異,首先下載安裝MySQLDriverCS后得到動態鏈接庫文件:
http://sourceforge.net/projects/mysqldrivercs/
將MySQLDriverCS.dll添加到工程的引用中:
還是利用上買呢已經在MySQL數據庫中建立了的測試數據,所以直接編寫C#代碼:
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));//讀出查詢的結果 } Console.ReadKey(); reader.Close(); conn.Close();//關閉連接 } 執行結果:
數據被成功讀出。




























