C#连接MySQL数据库(增删改查)

using System;
using MySql.Data.MySqlClient;

namespace CSharp直接连接MySQL
{
    class Program
    {
        static void Main(string[] args)
        {
            //Read();
            //Insert();
            //Update();
            //Delete();
            //ExcuteSccalar();//查询一个值更方便
            Console.WriteLine(VerifyUser("w", "2"));//验证库中是否有此数据
            Console.ReadKey();
        }
        static bool VerifyUser(string username, string password)
        {
            string connectStr = "server=127.0.0.1;port=3306;database=zxw;user=root;password=123456";//本机配置
            MySqlConnection conn = new MySqlConnection(connectStr);
            try
            {
                conn.Open();//开启数据库
                Console.WriteLine("已连接。。");
                //string sql = "select * from users where username='" + username + "' and password='" + password + "'";//按照自定义查询规则组拼sql
                string sql = "select * from users where username=@username and password=@password";//按照自定义查询规则组拼sql @符号等于临时定义一个数据
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("username", username);//给sql语句中的@定义赋值
                cmd.Parameters.AddWithValue("password", password);//给sql语句中的@定义赋值
                MySqlDataReader reader = cmd.ExecuteReader();//查询
                if (reader.Read()) return true;
                else return false;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            conn.Close();//关闭连接
            return false;
        }
        static void Read()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=zxw;user=root;password=123456";//本机配置
            MySqlConnection conn = new MySqlConnection(connectStr);
            try
            {
                conn.Open();//开启数据库
                Console.WriteLine("已连接。。");
                string sql = "select * from users";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                MySqlDataReader reader = cmd.ExecuteReader();//查询
                while (reader.Read())//Read()返回值bool
                {
                    //Console.WriteLine(reader[0].ToString() + "  " + reader[1].ToString() + "  " + reader[2].ToString());//通过read数组取值
                    //Console.WriteLine(reader.GetString(0) + "  " + reader.GetString(1) + "  " + reader.GetInt16(2));//通过get方法读取
                    Console.WriteLine(reader.GetString("username") + "  " + reader.GetString("password") + "  " + reader.GetInt16("id"));//通过列名索引读取
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            conn.Close();//关闭连接
            Console.ReadKey();
        }
        static void Insert()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=zxw;user=root;password=123456";//本机配置
            MySqlConnection conn = new MySqlConnection(connectStr);
            try
            {
                conn.Open();//开启数据库
                Console.WriteLine("已连接。。");
                string sql = "insert into users(username,password) values('" + DateTime.Now + "','zxw')";//当前时间
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                int result = cmd.ExecuteNonQuery();//返回值受数据库中数据的行数影响
                Console.WriteLine("插入完成");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            conn.Close();//关闭连接
            Console.ReadKey();
        }
        static void Update()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=zxw;user=root;password=123456";//本机配置
            MySqlConnection conn = new MySqlConnection(connectStr);
            try
            {
                conn.Open();//开启数据库
                Console.WriteLine("已连接。。");
                string sql = "update users set username='oo',password='oo' where id=1";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                int result = cmd.ExecuteNonQuery();//返回值受数据库中数据的行数影响
                Console.WriteLine("更新完成");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            conn.Close();//关闭连接
            Console.ReadKey();
        }
        static void Delete()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=zxw;user=root;password=123456";//本机配置
            MySqlConnection conn = new MySqlConnection(connectStr);
            try
            {
                conn.Open();//开启数据库
                Console.WriteLine("已连接。。");
                string sql = "delete from users where id=1";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                int result = cmd.ExecuteNonQuery();//返回值受数据库中数据的行数影响
                Console.WriteLine("删除完成");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            conn.Close();//关闭连接
            Console.ReadKey();
        }
        static void ExcuteSccalar()
        {
            string connectStr = "server=127.0.0.1;port=3306;database=zxw;user=root;password=123456";//本机配置
            MySqlConnection conn = new MySqlConnection(connectStr);
            try
            {
                conn.Open();//开启数据库
                Console.WriteLine("已连接。。");
                string sql = "select count(*) from users";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                object o = cmd.ExecuteScalar();//返回值即为查询结果
                int count = Convert.ToInt32(o.ToString());
                Console.WriteLine(count);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            conn.Close();//关闭连接
            Console.ReadKey();
        }
    }
}

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中进行 MySQL 数据库增删改查操作,你可以使用 MySQL Connector/NET 这个官方提供的 ADO.NET 驱动程序。以下是一个简单的示例: 首先,确保你已经安装了 MySQL Connector/NET。你可以在 NuGet 包管理器中搜索并安装 "MySql.Data"。 接下来,在你的项目中引入以下命名空间: ```csharp using MySql.Data.MySqlClient; ``` 连接数据库: ```csharp string connectionString = "server=localhost;user=root;password=your_password;database=your_database;"; using MySqlConnection connection = new MySqlConnection(connectionString); connection.Open(); ``` 插入数据: ```csharp string insertQuery = "INSERT INTO your_table (column1, column2) VALUES (@value1, @value2)"; using MySqlCommand command = new MySqlCommand(insertQuery, connection); command.Parameters.AddWithValue("@value1", "value1"); command.Parameters.AddWithValue("@value2", "value2"); command.ExecuteNonQuery(); ``` 更新数据: ```csharp string updateQuery = "UPDATE your_table SET column1 = @new_value WHERE column2 = @condition"; using MySqlCommand command = new MySqlCommand(updateQuery, connection); command.Parameters.AddWithValue("@new_value", "new_value"); command.Parameters.AddWithValue("@condition", "condition"); command.ExecuteNonQuery(); ``` 删除数据: ```csharp string deleteQuery = "DELETE FROM your_table WHERE column1 = @condition"; using MySqlCommand command = new MySqlCommand(deleteQuery, connection); command.Parameters.AddWithValue("@condition", "condition"); command.ExecuteNonQuery(); ``` 查询数据: ```csharp string selectQuery = "SELECT * FROM your_table"; using MySqlCommand command = new MySqlCommand(selectQuery, connection); using MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { string column1Value = reader.GetString("column1"); string column2Value = reader.GetString("column2"); // 执行你的逻辑 } ``` 最后,记得在不再需要连接时关闭连接: ```csharp connection.Close(); ``` 请注意,上述示例只是一个基本的示例,你需要根据你的具体情况进行修改。另外,为了安全起见,你应该避免直接将用户输入拼接到 SQL 查询中,而是使用参数化查询来防止 SQL 注入攻击。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值