使用MySQLConnectorNet連接MySQL數(shù)據(jù)庫
1.首先下載安裝Connector/Net,http://www.mysql.com/downloads/connector/net/
并從安裝目錄中得到所需動態(tài)鏈接庫MySql.Data.dll,如果已經(jīng)有MySql.Data.dll也可以不用安裝。

2.在項目中添加對該動態(tài)鏈接庫的引用


3.在mySQL中建一些測試數(shù)據(jù)如:
我是使用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;";//指明要連接的數(shù)據(jù)庫地址,用戶名,數(shù)據(jù)庫名,端口,密碼 MySqlConnection conn = new MySqlConnection(url);//實例化連接 conn.Open();//打開連接 string sta = "select * from stuinfo";//執(zhí)行一個簡單的語句 MySqlCommand comm = new MySqlCommand(sta, conn); MySqlDataReader reader = comm.ExecuteReader();//用MySqlDataReader接收執(zhí)行結(jié)果 while (reader.Read()) { Console.WriteLine(reader.GetString(0) + " " + reader.GetString(1) + " " + reader.GetString(2) +" " + reader.GetString(3));//讀出查詢的結(jié)果 } Console.ReadKey(); reader.Close(); conn.Close();//關(guān)閉連接 } 
使用MySQLDriverCS連接MySQL數(shù)據(jù)庫
與使用MySQLConnectorNet大同小異,首先下載安裝MySQLDriverCS后得到動態(tài)鏈接庫文件:
http://sourceforge.net/projects/mysqldrivercs/

將MySQLDriverCS.dll添加到工程的引用中:

還是利用上買呢已經(jīng)在MySQL數(shù)據(jù)庫中建立了的測試數(shù)據(jù),所以直接編寫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));//讀出查詢的結(jié)果 } Console.ReadKey(); reader.Close(); conn.Close();//關(guān)閉連接 } 執(zhí)行結(jié)果:

數(shù)據(jù)被成功讀出。
新聞熱點(diǎn)
疑難解答
圖片精選