C#連接MySQL數據庫
連接數據庫、執行sql語句需要的API,數據庫都有提供相關動態鏈接庫。
幫助文檔在C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation下的ConnectorNET.chm
1.添加動態鏈接庫文件:
安裝數據庫MySQL時要選中Connector.NET 6.9的安裝,將C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies裏v4.0或v4.5中的MySql.Data.dll導入項目。v4.0和v4.5,對應Visual Studio具體項目 屬性-應用程序-目標框架 裏的.NET Framework的版本號
2.建立連接(MySqlConnection)
using MySql.Data.MySqlClient; String connetStr = "server=127.0.0.1;port=3306;user=root;password=root; database=minecraftdb;"; // server=127.0.0.1/localhost 代表本機,端口號port默認是3306可以不寫 MySqlConnection conn = new MySqlConnection(connetStr); try { conn.Open();//打開通道,建立連接,可能出現異常Console.WriteLine("已經建立連接"); //在這裏使用代碼對數據庫進行增刪查改 } catch (MySqlException ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); }
3.捕捉異常(MySqlException)
連接錯誤時MySqlConnection會返回一個MySqlException,其中包括2個變量:
Message: A message that describes the current exception.
Number: The MySQL error number. (0: Cannot connect to server. 1045: Invalid user name and/or password.)
catch (MySqlException ex) { switch (ex.Number) { case 0: Console.WriteLine("Cannot connect to server. Contact administrator"); break; case 1045: Console.WriteLine("Invalid username/password, please try again"); break; } }
4.增刪查改的代碼(MySqlCommand、MySqlDataReader)
(1) 查詢
查詢條件固定
string sql= "select * from user"; MySqlCommand cmd = new MySqlCommand(sql,conn); MySqlDataReader reader =cmd.ExecuteReader();//ExecuteReader()用於生成一個MySqlDataReader對象 while (reader.Read())//讀取下一頁數據,返回值是bool { //Console.WriteLine(reader[0].ToString() + reader[1].ToString() + reader[2].ToString()); //Console.WriteLine(reader.GetInt32(0)+reader.GetString(1)+reader.GetString(2)); Console.WriteLine(reader.GetInt32("userid") + reader.GetString("username") + reader.GetString("password"));//推薦這種方式 }
需要查詢返回一個值
string sql = "select count(*) from user"; MySqlCommand cmd = new MySqlCommand(sql, conn); Object result=cmd.ExecuteScalar();//執行查詢,並返回查詢所返回的結果集中第一行的第一列。所有其他的列和行將被忽略。select語句無記錄返回時,ExecuteScalar()返回NULL值 if (result != null) { int count = int.Parse(result.ToString()); }
查詢條件不固定
//string sql = "select * from user where username=‘"+username+"‘ and password=‘"+password+"‘"; //我們自己按照查詢條件去組拼 string sql = "select * from user where username=@para1 and password=@para2";//在sql語句中定義parameter,然後再給parameter賦值 MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.Parameters.AddWithValue("para1", username); cmd.Parameters.AddWithValue("para2", password); MySqlDataReader reader = cmd.ExecuteReader(); if (reader.Read())//如果用戶名和密碼正確則能查詢到一條語句,即讀取下一行返回true { return true; }
(2) 插入、刪除、更改
string sql = "insert into user(username,password,registerdate) values(‘啊寬‘,‘123‘,‘"+DateTime.Now+"‘)"; //string sql = "delete from user where userid=‘9‘"; //string sql = "update user set username=‘啊哈‘,password=‘123‘ where userid=‘8‘"; MySqlCommand cmd = new MySqlCommand(sql,conn); int result =cmd.ExecuteNonQuery();//3.執行插入、刪除、更改語句。執行成功返回受影響的數據的行數,返回1可做true判斷。執行失敗不返回任何數據,報錯,下面代碼都不執行
5.事務(MySqlTransaction)
String connetStr = "server=127.0.0.1;user=root;password=root;database=minecraftdb;"; MySqlConnection conn = new MySqlConnection(connetStr); conn.Open();//必須打開通道之後才能開始事務 MySqlTransaction transaction = conn.BeginTransaction();//事務必須在try外面賦值不然catch裏的transaction會報錯:未賦值 Console.WriteLine("已經建立連接"); try { string date = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day; string sql1= "insert into user(username,password,registerdate) values(‘啊寬‘,‘123‘,‘" + date + "‘)"; MySqlCommand cmd1 = new MySqlCommand(sql1,conn); cmd1.ExecuteNonQuery(); string sql2 = "insert into user(username,password,registerdate) values(‘啊寬‘,‘123‘,‘" + date + "‘)"; MySqlCommand cmd2 = new MySqlCommand(sql2, conn); cmd2.ExecuteNonQuery(); } catch (MySqlException ex) { Console.WriteLine(ex.Message); transaction.Rollback();//事務ExecuteNonQuery()執行失敗報錯,username被設置unique conn.Close(); } finally { if (conn.State != ConnectionState.Closed) { transaction.Commit();//事務要麽回滾要麽提交,即Rollback()與Commit()只能執行一個 conn.Close(); } }
總結:
MySQL動態鏈接庫提供了8個類,而上面常用操作只用到了這4個類
(1)MySqlConnection: 連接MySQL服務器數據庫。
(2)MySqlCommand:執行一條sql語句
a.ExecuteReader——用於查詢數據庫。結果通常是MySqlDataReader對象中返回。
b.ExecuteNonQuery——用於插入和刪除數據。
c.ExecuteScalar——用於返回一個值。
(3)MySqlDataReader: 包含sql語句執行的結果,並提供一個方法從結果中閱讀一行
(4)MySqlTransaction: 代表一個SQL事務在一個MySQL數據庫。
(5)MySqlException: MySQL報錯時返回的Exception
還有這3個類 的相關操作未涉及, 大家可以去看幫助文檔ConnectorNET.chm在C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation裏面
MySqlCommandBuilder: Automatically generates single-table commands used to reconcile changes made to a DataSet with the associated MySQL database.
MySqlDataAdapter: Represents a set of data commands and a database connection that are used to fill a data set and update a MySQL database.
MySqlHelper: Helper class that makes it easier to work with the provider.
C#連接MySQL數據庫