本文實例講述了C#連接mysql的方法。分享給大家供大家參考,具體如下:
在vs2010中 工具->數據庫連接 里要想連接到MySQL數據庫,需要安裝這樣一個東西: MySql Connector;
1.首先安裝 connector 。下載地址:(http://www.mysql.com/downloads/connector/net/)
2.現在就可以了,打開vs2010試試吧!
安裝完成后找到安裝目錄下(C:/Program Files/MySQL/MySQL Connector Net 6.4.4/Assemblies/v4.0/MySql.Data.dll,添加引用到工程中.
現在一切就OK了!
如果想在工程c#中連接mysql,需如下代碼:
//define the connection reference and initialize itMySql.Data.MySqlClient.MySqlConnection msqlConnection = null;msqlConnection = new MySql.Data.MySqlClient.MySqlConnection("server=localhost;user id=UserName;Password=UserPassword;database=DatabaseName;persist security info=False");//define the command referenceMySql.Data.MySqlClient.MySqlCommand msqlCommand = new MySql.Data.MySqlClient.MySqlCommand();//define the connection used by the command objectmsqlCommand.Connection = this.msqlConnection;//define the command textmsqlCommand.CommandText = "SELECT * FROM TestTable;";try{ //open the connection this.msqlConnection.Open(); //use a DataReader to process each record MySql.Data.MySqlClient.MySqlDataReader msqlReader = msqlCommand.ExecuteReader(); while (msqlReader.Read()) { //do something with each record }}catch (Exception er){ //do something with the exception}finally{ //always close the connection this.msqlConnection.Close();}
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答