C#与MySql连接

MySQL与C#连接的动态链接库。

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

如果版本不是NET6.9,可以在Visual Studio,在 项目(右键)-管理NuGet程序包(N) 然后在浏览里面搜索MySql.Data并进行安装。

连接数据库、操作数据库,本质是利用数据库提供的动态链接库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.

如何将C#与数据库连接:

步骤1:创建访问数据库的对象(Connection)

//步骤1:创建访问数据库的对象(Connection)
string connetStr = "server=127.0.0.1;port=3306;user=root;password=root; database=experiment_4;";
// server=127.0.0.1/localhost 代表本机,端口号port默认,database是访问的数据库
MySqlConnection conn = new MySqlConnection(connetStr);

步骤2,3,4:打开数据库,创建脚本对象,使用代码实现对MySql的操作

try{
    conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句
    Console.WriteLine("已经建立连接");

    //步骤3:创建执行脚本对象 
    //ExecuteReader(多行多列游标对象,易错)
    //ExecuteNonQuery(单行单列 添加 删除 修改)
    //ExecuteScalar(单行单列 查询)
    //查找单行单列
    string sql1 = "select max(id) from goods";
    MySqlCommand cmd1 = new MySqlCommand(sql1,conn);
    Object obj = cmd1.ExecuteScalar();//object 是所有类型的基类
    Console.WriteLine($"最大编号:{obj}");
    //添加 删除 修改
     /*
     string sql2 = "delete goods where id = 1;";
     int result=cmd2.ExecuteScalar(sql2,conn);
     if (result > 0) Console.WriteLine("删除成功!");
     else Console.WriteLine("删除失败!");
   */
    /*
    //查询多行多列
    string sql3 = "select * from goods;";
    MySqlCommand cmd3 = new MySqlCommand(sql3, conn);
    //MySqlDataReader 数据库中只读的游标对象 read()==next(); prve();
    MySqlDataReader reader = cmd3.ExecuteReader();//执行ExecuteReader()返回一个MySqlDataReader对象
  while (reader.Read()) {
        Console.WriteLine(reader.GetInt32("id") + reader.GetString("name") + reader.GetString("price"));
        }
    reader.Close();//释放游标对象
    */

    //步骤4:在这里使用代码对数据库进行增删查改


            }
    catch (MySqlException ex)//捕获异常
    {
           Console.WriteLine(ex.Message);
     }
    finally
            {
                conn.Close();
                Console.WriteLine("连接结束");
                Console.ReadLine();
            }

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐