欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#如何連接MySQL數(shù)據(jù)庫(kù)

 更新時(shí)間:2020年10月12日 14:56:49   作者:千里Z單騎  
這篇文章主要介紹了C#如何連接MySQL數(shù)據(jù)庫(kù),幫助大家更好的理解和使用c#,感興趣的朋友可以了解下

本文章是建立在已經(jīng)安裝MySQL數(shù)據(jù)庫(kù)的前提,默認(rèn)安裝在C:\Program Files (x86)\MySQL,建議在安裝時(shí)選中Connector.NET 6.9的安裝,里面有MySQL與C#連接的動(dòng)態(tài)鏈接庫(kù)。

  幫助文檔C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation\ConnectorNET.chm是我撰寫(xiě)此文章的主要依據(jù)。其中Users Guide下,Programming是對(duì)動(dòng)態(tài)鏈接庫(kù)8個(gè)類的介紹,Tutorial是案例代碼。

  連接數(shù)據(jù)庫(kù)、操作數(shù)據(jù)庫(kù),本質(zhì)是利用數(shù)據(jù)庫(kù)提供的動(dòng)態(tài)鏈接庫(kù)MySql.Data.dll進(jìn)行操作。MySql.Data.dll提供以下8個(gè)類:

  • MySqlConnection: 連接MySQL服務(wù)器數(shù)據(jù)庫(kù)。
  • MySqlCommand:執(zhí)行一條sql語(yǔ)句。
  • MySqlDataReader: 包含sql語(yǔ)句執(zhí)行的結(jié)果,并提供一個(gè)方法從結(jié)果中閱讀一行。
  • MySqlTransaction: 代表一個(gè)SQL事務(wù)在一個(gè)MySQL數(shù)據(jù)庫(kù)。
  • MySqlException: MySQL報(bào)錯(cuò)時(shí)返回的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.添加動(dòng)態(tài)鏈接庫(kù)文件

  方法一:Visual Studio,在 項(xiàng)目(右鍵)-管理NuGet程序包(N) 然后在瀏覽里面搜索MySql.Data并進(jìn)行安裝。

  方法二:安裝數(shù)據(jù)庫(kù)MySQL時(shí)要選中Connector.NET 6.9的安裝,將C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies里v4.0或v4.5中的MySql.Data.dll添加到項(xiàng)目的引用。v4.0和v4.5,對(duì)應(yīng)Visual Studio具體項(xiàng)目 屬性-應(yīng)用程序-目標(biāo)框架 里的.NET Framework的版本號(hào)。

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 代表本機(jī),端口號(hào)port默認(rèn)是3306可以不寫(xiě)
MySqlConnection conn = new MySqlConnection(connetStr);
try
{  
   conn.Open();//打開(kāi)通道,建立連接,可能出現(xiàn)異常,使用try catch語(yǔ)句
   Console.WriteLine("已經(jīng)建立連接");
   //在這里使用代碼對(duì)數(shù)據(jù)庫(kù)進(jìn)行增刪查改
}
catch (MySqlException ex)
{
   Console.WriteLine(ex.Message);
}
finally
{
   conn.Close();
}

3.捕捉異常(MySqlException類)

  連接錯(cuò)誤時(shí)MySqlConnection會(huì)返回一個(gè)MySqlException,其中包括2個(gè)變量:

  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——用于查詢數(shù)據(jù)庫(kù)。查詢結(jié)果是返回MySqlDataReader對(duì)象,MySqlDataReader包含sql語(yǔ)句執(zhí)行的結(jié)果,并提供一個(gè)方法從結(jié)果中閱讀一行。

  ExecuteNonQuery——用于插入、更新和刪除數(shù)據(jù)。

  ExecuteScalar——用于查詢數(shù)據(jù)時(shí),返回查詢結(jié)果集中第一行第一列的值,即只返回一個(gè)值。

  (1) 查詢

  a.查詢條件固定

string sql= "select * from user";
MySqlCommand cmd = new MySqlCommand(sql,conn);
MySqlDataReader reader =cmd.ExecuteReader();//執(zhí)行ExecuteReader()返回一個(gè)MySqlDataReader對(duì)象
while (reader.Read())//初始索引是-1,執(zhí)行讀取下一行數(shù)據(jù),返回值是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"是數(shù)據(jù)庫(kù)對(duì)應(yīng)的列名,推薦這種方式
}

b.查詢條件不固定

//string sql = "select * from user where username='"+username+"' and password='"+password+"'"; //我們自己按照查詢條件去組拼
string sql = "select * from user where username=@para1 and password=@para2";//在sql語(yǔ)句中定義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())//如果用戶名和密碼正確則能查詢到一條語(yǔ)句,即讀取下一行返回true
{
  return true;
}

c.需要查詢返回一個(gè)值

string sql = "select count(*) from user";
MySqlCommand cmd = new MySqlCommand(sql, conn);
Object result=cmd.ExecuteScalar();//執(zhí)行查詢,并返回查詢結(jié)果集中第一行的第一列。所有其他的列和行將被忽略。select語(yǔ)句無(wú)記錄返回時(shí),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.執(zhí)行插入、刪除、更改語(yǔ)句。執(zhí)行成功返回受影響的數(shù)據(jù)的行數(shù),返回1可做true判斷。執(zhí)行失敗不返回任何數(shù)據(jù),報(bào)錯(cuò),下面代碼都不執(zhí)行

5.事務(wù)(MySqlTransaction類)

String connetStr = "server=127.0.0.1;user=root;password=root;database=minecraftdb;";
MySqlConnection conn = new MySqlConnection(connetStr);
conn.Open();//必須打開(kāi)通道之后才能開(kāi)始事務(wù)
MySqlTransaction transaction = conn.BeginTransaction();//事務(wù)必須在try外面賦值不然catch里的transaction會(huì)報(bào)錯(cuò):未賦值
Console.WriteLine("已經(jīng)建立連接");
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();//事務(wù)ExecuteNonQuery()執(zhí)行失敗報(bào)錯(cuò),username被設(shè)置unique
  conn.Close();
}
finally
{
  if (conn.State != ConnectionState.Closed)
  {
    transaction.Commit();//事務(wù)要么回滾要么提交,即Rollback()與Commit()只能執(zhí)行一個(gè)
    conn.Close();
  }
}

結(jié)語(yǔ):連接數(shù)據(jù)庫(kù)、操作數(shù)據(jù)庫(kù),本質(zhì)是利用數(shù)據(jù)庫(kù)提供的動(dòng)態(tài)鏈接庫(kù)MySql.Data.dll進(jìn)行操作。動(dòng)態(tài)鏈接庫(kù)中的8個(gè)類上面常用操作只用到了類1-5,類6-8 的相關(guān)操作未涉及, 大家可以去看幫助文檔C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation\ConnectorNET.chm學(xué)習(xí)。

以上就是C#如何連接MySQL數(shù)據(jù)庫(kù)的詳細(xì)內(nèi)容,更多關(guān)于C#連接MySQL的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論