如果需要查看更多文章,請微信搜索公眾號 csharp編程大全,需要進C#交流群群請加微信z438679770,備注進群, 我邀請你進群! ! !
------------------------------------------------------------------------------------------------------------------------------
本文章是建立在已經安裝MySQL資料庫的前提,默認安裝在C:\Program Files (x86)\MySQL,建議在安裝時選中Connector.NET 6.9的安裝,里面有MySQL與C#連接的元件,
幫助檔案C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation\ConnectorNET.chm是我撰寫此文章的主要依據,其中Users Guide下,Programming是對元件8個類的介紹,Tutorial是案例代碼,
連接資料庫、操作資料庫,本質是利用資料庫提供的元件MySql.Data.dll進行操作,MySql.Data.dll提供以下8個類:
MySqlConnection: 連接MySQL服務器資料庫, MySqlCommand:執行一條sql陳述句, MySqlDataReader: 包含sql陳述句執行的結果,并提供一個方法從結果中閱讀一行, MySqlTransaction: 代表一個SQL事務在一個MySQL資料庫, MySqlException: MySQL報錯時回傳的Exception, 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
1.添加元件檔案
方法一:Visual Studio,在 專案(右鍵)-管理NuGet程式包(N) 然后在瀏覽里面搜索MySql.Data并進行安裝,
方法二:安裝資料庫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();//打開通道,建立連接,可能出現例外,使用try catch陳述句
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類)
ExecuteReader——用于查詢資料庫,查詢結果是回傳MySqlDataReader物件,MySqlDataReader包含sql陳述句執行的結果,并提供一個方法從結果中閱讀一行,
ExecuteNonQuery——用于插入、更新和洗掉資料,
ExecuteScalar——用于查詢資料時,回傳查詢結果集中第一行第一列的值,即只回傳一個值,
(1) 查詢
a.查詢條件固定
string sql= "select * from user";
MySqlCommand cmd = new MySqlCommand(sql,conn);
MySqlDataReader reader =cmd.ExecuteReader();//執行ExecuteReader()回傳一個MySqlDataReader物件
while (reader.Read())//初始索引是-1,執行讀取下一行資料,回傳值是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"));//"userid"是資料庫對應的列名,推薦這種方式
}
b.查詢條件不固定
//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;
}
c.需要查詢回傳一個值
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());
}
(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類)
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.Data.dll進行操作,元件中的8個類上面常用操作只用到了類1-5,類6-8 的相關操作未涉及, 大家可以去看幫助檔案C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation\ConnectorNET.chm學習,
本文鏈接:
https://www.cnblogs.com/LessNull/p/11286387.html
如果需要查看更多文章,請微信搜索公眾號 csharp編程大全,需要進C#交流群群請加微信z438679770,備注進群, 我邀請你進群! ! !
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/168969.html
標籤:.NET技术
下一篇:C# 主界面的扁平化
