C# MySQL 参数化查询方式

C# MySQL 参数化查询方式
using System;
using MySql.Data.MySqlClient;
 
namespace MySqlDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "server=127.0.0.1;port=3306;database=test_db;charset=utf8;user id=root;password=123456;pooling=false;";
            string sqlstring = "INSERT INTO users(name,sex) VALUES (@name,@sex);";
 
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    conn.Open();
                    cmd.Connection = conn;
                    cmd.CommandText = sqlstring;
                    cmd.CommandType = System.Data.CommandType.Text;
 
                    // 绑定参数
                    cmd.Parameters.AddWithValue("@name", "Nancy");
                    cmd.Parameters.AddWithValue("@sex", "Female");
 
                    try
                    {
                        // 返回受影响的行数, 执行INSERT语句, 返回创建条目数
                        //                  执行UPDATE语句, 返回更新条目数
                        //                  执行DELETE语句, 返回删除条目数
                        int val = cmd.ExecuteNonQuery();
                        Console.WriteLine(val);
                    }
                    catch
                    {
                        throw;
                    }
                }
            }
 
            Console.Read();
        }
    }
}

热门推荐