【MySQL】C# 连接MySQL

C# 连接MySQL

1. 添加MySQL引用

安装完MySQL之后,在安装的默认目录 C:\Program Files (x86)\MySQL\Connector NET 8.0 中查找MySQLData.dll文件。

在Visual Studio 中为项目中添加引用。

2. 引入命名空间

csharp 复制代码
using MySql.Data.MySqlClient;

3. 构建连接

csharp 复制代码
private static MySqlConnection m_Connect = null;
private static void Connect()
{
    string connectStr = "server=127.0.0.1;port=3306;database=test;user=root;password=root;";
    m_Connect = new MySqlConnection(connectStr);
}
server=IP地址;
port=端口号;
database=数据库名字;
user=管理员账号;
password=账号的密码;

4. 增删改查

csharp 复制代码
private static void Insert()
{
    try
    {
        m_Connect.Open();
        //string sqlStr = "Insert into users(username, password) values('takil', '789')";
        //string sqlStr = "Insert into users(username, password, registerdate) values('taksil', '789789', '2015-05-09')";
        string sqlStr = "Insert into users(username, password, registerdate) values('wilhelm', '78889', '" + DateTime.Now + "')";
       
        MySqlCommand cmd = new MySqlCommand(sqlStr, m_Connect);
        int result = cmd.ExecuteNonQuery();
        Console.WriteLine("成功影响了{0}条数据", result);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    {
        m_Connect?.Close();
    }
}

csharp 复制代码
private static void Delete()
{
    try
    {
        m_Connect.Open();
        string sql = "delete from users where username = 'takil'";

        
        MySqlCommand cmd = new MySqlCommand(sql, m_Connect);
        int result = cmd.ExecuteNonQuery();
        Console.WriteLine("成功影响了{0}条数据", result);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    { m_Connect?.Close(); }
}

csharp 复制代码
private static void Update()
{
    try
    {
        m_Connect.Open();
        string sql = "Update users set username = 'wqrwq', password = '123' where id = 5";

        MySqlCommand cmd = new MySqlCommand( sql, m_Connect);
        int result = cmd.ExecuteNonQuery();
        Console.WriteLine("成功影响了{0}条数据", result);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    { m_Connect?.Close(); }
}

csharp 复制代码
private static void Read()
{
    try
    {
        m_Connect.Open();
        string sqlStr = "select * from users";
        //string sqlStr = "select id, username, registerdate from users";
        
        MySqlCommand cmd = new MySqlCommand(sqlStr, m_Connect);
        MySqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            //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("id") + " " + reader.GetString("username") + " " + reader.GetString("password"));
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    {
        m_Connect?.Close();
    }
}
csharp 复制代码
private static void ReadCount()
{
    try
    {
        m_Connect.Open();
        string sqlStr = "select Count(*) from users";
        MySqlCommand cmd = new MySqlCommand(sqlStr, m_Connect);

        //MySqlDataReader reader = cmd.ExecuteReader();
        //reader.Read();
        //int count = Convert.ToInt32(reader[0]);
        //Console.WriteLine("总数为{0}", count);

        object result = cmd.ExecuteScalar();
        int count = Convert.ToInt32(result);
        Console.WriteLine("总数为{0}", count);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    { m_Connect?.Close(); }
}

验证

csharp 复制代码
private static bool ValifyUser(string username, string password)
{
    try
    {
        m_Connect.Open();
        //string sqlStr = "select * from users where username = '" + username + "' and password = '" + password + "'";
        string sqlStr = "select * from users where username = @para1 and password = @para2";

        MySqlCommand cmd = new MySqlCommand(sqlStr, m_Connect);

        cmd.Parameters.AddWithValue("para1", username);
        cmd.Parameters.AddWithValue("para2", password);

        MySqlDataReader reader = cmd.ExecuteReader();
        if(reader.Read())
        {
            return true;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    {
        m_Connect?.Close();
    }
    return false;
}

因为作者精力有限,文章中难免出现一些错漏,敬请广大专家和网友批评、指正。

相关推荐
秃头佛爷1 小时前
Python学习大纲总结及注意事项
开发语言·python·学习
待磨的钝刨1 小时前
【格式化查看JSON文件】coco的json文件内容都在一行如何按照json格式查看
开发语言·javascript·json
△曉風殘月〆2 小时前
WPF MVVM入门系列教程(二、依赖属性)
c#·wpf·mvvm
XiaoLeisj3 小时前
【JavaEE初阶 — 多线程】单例模式 & 指令重排序问题
java·开发语言·java-ee
励志成为嵌入式工程师4 小时前
c语言简单编程练习9
c语言·开发语言·算法·vim
逐·風4 小时前
unity关于自定义渲染、内存管理、性能调优、复杂物理模拟、并行计算以及插件开发
前端·unity·c#
捕鲸叉4 小时前
创建线程时传递参数给线程
开发语言·c++·算法
A charmer4 小时前
【C++】vector 类深度解析:探索动态数组的奥秘
开发语言·c++·算法
Peter_chq4 小时前
【操作系统】基于环形队列的生产消费模型
linux·c语言·开发语言·c++·后端
Yaml45 小时前
Spring Boot 与 Vue 共筑二手书籍交易卓越平台
java·spring boot·后端·mysql·spring·vue·二手书籍