【MySQL】C# 连接MySQL

C# 连接MySQL

1. 添加MySQL引用

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

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

2. 引入命名空间

using MySql.Data.MySqlClient;

3. 构建连接

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. 增删改查

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();
    }
}
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(); }
}
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(); }
}
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();
    }
}


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(); }
}
验证
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;
}

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

相关推荐
CC呢10 分钟前
基于STM32单片机火灾安全监测一氧化碳火灾
数据库·mongodb
MasterNeverDown38 分钟前
解决 PostgreSQL 中创建 TimescaleDB 扩展的字符串错误
数据库·postgresql·oracle
limts1 小时前
Oracle之开窗函数使用
数据库·oracle
code_shenbing2 小时前
C# 操作 文件
开发语言·c#
拾荒的小海螺3 小时前
JAVA:Spring WebClient 的应用指南
java·数据库·spring
LuckyRich13 小时前
2024年博客之星主题创作|2024年度感想与新技术Redis学习
数据库·redis·缓存
code_shenbing3 小时前
基于 WPF 平台使用纯 C# 实现动态处理 json 字符串
c#·json·wpf
重整旗鼓~3 小时前
4.flask-SQLAlchemy,表Model定义、增删查改操作
数据库·python·flask
咩咩大主教3 小时前
Go语言通过Casbin配合MySQL和Gorm实现RBAC访问控制模型
mysql·golang·鉴权·go语言·rbac·abac·casbin
PGCCC4 小时前
【PGCCC】PostgreSQL 中表级锁的剖析
数据库·postgresql·区块链