C#连接MySQL数据库

时间:2022-07-23
本文章向大家介绍C#连接MySQL数据库,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文章是建立在已经安装MySQL数据库的前提,默认安装在C:Program Files (x86)MySQL,建议在安装时选中Connector.NET 6.9的安装,里面有MySQL与C#连接的动态链接库。

  帮助文档C:Program Files (x86)MySQLConnector.NET 6.9DocumentationConnectorNET.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)MySQLConnector.NET 6.9Assemblies里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类)

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)MySQLConnector.NET 6.9DocumentationConnectorNET.chm学习。

本文链接:

https://www.cnblogs.com/LessNull/p/11286387.html