C#安装 MySQL 驱动以及实现简单的 MySQL 操作

332 阅读4分钟

一、驱动下载

首先前往 MySql 官网下载驱动。下载地址:dev.mysql.com/downloads/c…

img

注意驱动版本即可。注意:要下载.zip 版本,解压后会看到几个 dll,那个就是需要的驱动

img

最新的 8.0.16 版本驱动要求.net 版本在 4.5 以上,如果需要 4.0 版本的则需要 6.8.8 版本,选择 4.0 版本驱动即可

image

img

由于本人安装的 Visual Studio 2010 最高只支持.net4.0,因此只能使用旧版驱动。不管哪个版本,MySQL 的核心驱动都是 MySql.Data.dll,使用的时候只需要引入这个即可

image

二、驱动引入

  1. 新建一个项目,名称随意。

img

  1. 找到项目位置,在项目根目录下新建 lib 文件夹

image

  1. 将 MySql.Data.dll 复制到该目录下

image

  1. 回到 Visual Studio 2010 中,右键添加添加引用

    image

  2. 选择浏览,找到 MySql.Data.dll,选中并点击确定

img

三、连接数据库

  1. 新建一个 Database.cs 类,并引用 MySql.Data.MySqlClient 类。注意类名前添加 public,否则无法在其他类中调用这个类

image

  1. 写一个初始化方法
 public class Database
 {
     static MySqlConnection conn;//MySql连接
     const String server = "localhost";//服务器地址
     const String uid = "test";//用户名
     const String pw = "123456";//密码
     const String db = "test";//库名
     /// <summary>
     /// 初始化程序,连接数据库
     /// </summary>
     public static Boolean Init()
     {
         try
         {
             if (conn == null)
             {
                 conn = new MySqlConnection("server=" + server + ";user id=" + uid + ";password=" + pw + ";database=" + db);
                 conn.Open();
                 Console.WriteLine("数据库连接成功");
             }
             return true;
         }
         catch (Exception e)//异常处理
         {
             Console.WriteLine("Exception caught: {0}", e);
             return false;
         }
     }
 }

​ 3. 在主程序中调用该方法,观察控制台是否有输出,如果显示“数据库连接成功”则表明数据库连接已成功,操作正确。

image

img

四、编写数据库操作辅助类

对数据库的操作有很多重复的内容,因此这些可以像初始化方法这样提取出来。

  1. 查询操作

    /// <summary>
    /// 查询操作,成功返回MySqlDataReader,具体的数据可以从该对象中获取;失败返回null
    /// </summary>
    public static MySqlDataReader Select(String sql)
    {
        try
        {
            Init();
            MySqlCommand command = new MySqlCommand(sql, conn);
            MySqlDataReader data = command.ExecuteReader();//这里返回从数据库获取的数据
            return data;
        }
        catch (Exception e)//注意了,对数据库的操作尤为要注意异常处理,因此直接写在这里即可
        {
            Console.WriteLine("Exception caught: {0}", e);
            return null;
        }
    }
    
  2. 增删改操作

    /// <summary>
    /// 执行一条sql指令,成功返回true,失败返回fasle
    /// 事实上
    /// </summary>
    public static Boolean DbOp(String sql)
    {
        try
        {
            Init();
            MySqlCommand command = new MySqlCommand(sql, conn);
            int result = command.ExecuteNonQuery();//这里返回的是受影响的数据条数,如果不为零则表明操作成功
            return result != 0;
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception caught: {0}", e);
            return false;
        }
    }
    
  3. 实现字符串的转义

    /// <summary>
    /// 转义字符串 例如 abc 转为 'abc'
    /// </summary>
    public static String Escape(Object str)
    {
        if (str.GetType() == "".GetType())
        {//是字符串的进行防注入
            return "'" + MySqlHelper.EscapeString(str.ToString()) + "'";//注意,MySQL中表示字符串时一定需要单引号或反引号
        }
        return str.ToString();
    }
    

五、实现简单的增删查改功能

  1. 数据表名称:user

    字段:id,类型 int;name,类型 text;pw,类型 text

    img

如果要用 sql 语句创建,可参考如下,也可以用可视化工具创建

CREATE TABLE IF NOT EXISTS `user`(
   `id` INT AUTO_INCREMENT PRIMARY KEY,
   `name` TEXT NOT NULL,
   `pw` TEXT NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
  1. 在项目中新建一个 User.cs 类,内容如下
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using MySql.Data.MySqlClient;
    
    namespace MySqlTest
    {
        class User
        {
            public int id;//编号
            public String name;//用户名
            public String pw;//密码
            public User()
            {
            }
            public User(MySqlDataReader data)
            {
                this.id = data.GetInt16("id");
                this.name = data.GetString("name");
                this.pw = data.GetString("pw");
            }
            public User(String name, String pw)//注册时需要创建无id的新用户
            {
                this.name = name;
                this.pw = pw;
            }
            public User(int id, String name, String pw)
            {
                this.id = id;
                this.name = name;
                this.pw = pw;
            }
        }
    }
    
  1. 实现 user 的查询
 /// <summary>
/// 根据id查找指定用户
/// </summary>
public static User SelectUser(int id)
{
    string sql = "SELECT * from user WHERE id = " + id;
    MySqlDataReader data = Select(sql);//如果出现异常会返回null,需要注意!!
    if (data != null && data.Read())
    {
        User user = new User(data);//由于上面已经在User的的构造函数中写了相关方法,所以这里直接调用即可
        data.Close();
        return user;
    }
    else
    {
        if (data != null) //如果不为空则需要关闭!
        { 
            data.Close(); 
        }
        return null;
    }
}

3.实现 user 的增加

 /// <summary>
/// 创建新用户
/// </summary>
public static User AddUser(User user)
{
    String sql = "INSERT into user(id,name,pw) values(0," + Escape(user.name) + "," + Escape(user.pw)  + ")";
    if (DbOp(sql))
    {
        return SelectUser(user.name);
    }
    else
    {
        return null;
    }
}

4.实现 user 的更新

/// <summary>
/// 修改用户
/// </summary>
public static Boolean UpdateUser(User user)
{
    String sql = "UPDATE user SET name = " + Escape(user.name) + ",pw = " + Escape(user.pw) +  " WHERE id = " + user.id;
    return DbOp(sql);
}

5.实现 user 的删除

/// <summary>
/// 删除用户
/// </summary>
public static Boolean DeleteUser(int id)
{
    String sql = "DELETE from user WHERE id = " + id;
    return DbOp(sql);
}

本文作者:草梅友仁
本文地址: blog.cmyr.ltd/archives/99…
版权声明:转载请注明出处!