C#执行带参数的mysql语句

本文介绍如何使用C#通过MySql.Data.dll连接MySQL数据库,并实现SQL语句参数化,有效避免SQL注入风险。文章详细展示了从连接配置、SQL语句编写到参数赋值及异常处理的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本教程用C# Connector/NET中的MySql.Data.dll连接mysql数据库,请做好相关配置后代码内引入:

using MySql.Data.MySqlClient;

最近在项目用C#调用mysql,执行的sql语句需要传输参数,搞了好久终于搞定了,记录下中间踩的坑,变量如下:

public static long fileid;
public static string type;
public static string police_name;
public static string linux_path;
public static int year;
public static int month;
public static int day;
public static int uploadtime;
///这些变量需要自己初始化

一.开启sql语句参数支持


 public static string mysql_url = "server=192.168.83.134;
 userid=root;database=hehe;
port=3306;password=test;Charset=utf8;
Allow User Variables=True";//连接mysql的字符串

注意这里的“Allow User Variables=True”,只有加上这句,后面才能执行带参数的sql语句。

二.用问号标识变量

MySqlConnection myConnnect = new MySqlConnection(mysql_url);  
myConnnect.Open();
string insert_str = "insert into        police_file(file_id,police_name,file_type,year,month,day,file_path,upload_time) values(?fileid,?police_name,?type,?year,?month,?day,?linux_path,?uploadtime) ";

MySqlCommand myCmd = new MySqlCommand(insert_str, myConnnect);

三.AddWithValue参数赋值:


myCmd.Parameters.AddWithValue("@fileid", fileid);
myCmd.Parameters.AddWithValue("@police_name", police_name);
myCmd.Parameters.AddWithValue("@type", type);
myCmd.Parameters.AddWithValue("@year", year);
myCmd.Parameters.AddWithValue("@month", month);
myCmd.Parameters.AddWithValue("@day", day);
myCmd.Parameters.AddWithValue("@linux_path", linux_path);
myCmd.Parameters.AddWithValue("@uploadtime", uploadtime);

四.执行sql语句

try
    {
        myCmd.ExecuteNonQuery();
    }
catch (System.Exception e)
    {
        MessageBox.Show(e.Message);
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值