C#创建一个使用MySQL的类

1.连接MySQL数据库

在这里插入图片描述

2.创建一个数据库类

//引用命名空间
using MySql.Data.MySqlClient;
//数据库类
class SQLDemo{
		MySql.Data.MySqlClient.MySqlConnection conn;//一个连接对象
	//数据库连接方法
		public MySqlConnection Connection()
        {
        	//创建一条string语句
            string connestStr = "data source = localhost; uid = 用户名; password = 密码; database =数据库;";
            //连接到数据库
            MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connestStr);
            conn.Open();//打开数据库
            this.conn = conn;
            return conn;
        }
        //关闭数据库
        public void Close()
        {
            this.conn.Close();
        }
     
        //返回数据库MySqlCommand类型,对应数据库后续的操作
        public MySqlCommand Command(string sql)
        {
        	//将SQL以及链接对象作为参数传入
            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
            MySql.Data.MySqlClient.MySqlDataAdapter sda = new MySql.Data.MySqlClient.MySqlDataAdapter();
            //向数据库发送查询语句
            sda.SelectCommand = cmd;
            return cmd;
        }
        //用于delete update insert
        //语句执行成功是返回值为该命令所影响的行数,如果影响的行数是0,则返回值就是0
        public int Excute(string sql)
        {
            return Command(sql).ExecuteNonQuery();
        }
        //用于select读取数据
        public MySqlDataReader read(string sql)
        {
            return Command(sql).ExecuteReader();
            //读到的数据全部获取
        }
}