C#——SqlParameter的使用方法及注意事项

SqlParameter可以防止sql注入问题,这里记录下使用方法及代码。

1.封装的sqlHelper类中的数据库操作方法(部分代码,具体可参见.net 使用SQLconnection连接数据库及SQL帮助类)
//这里要填入你的数据库连接字符串
private static string connectionString = "*************************";
        /// <summary>
        /// 执行增、删、改的方法
        /// </summary>
        /// <param name="sql">预计执行的非SELECT查询语句</param>
        /// <param name="param">SQL语句中的可变参数</param>
        /// <returns>返回受影响的行数</returns>
        public static int ExecuteNonQuery(string sql, params SqlParameter[] param)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                try
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddRange(param);
                    return cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("异常信息:\n" + ex.Message);
                    return -2;
                }
            }
        }
2.使用SqlParameter的代码:
        public static void TestSqlParameter()
        {

            string sqlValue = "insert into out_in_storage(day_night_shift,record_acc," +
                "record_name,handle_acc,handle_name,is_outed,product_line,fixure_id,log_time) " +
                "values(@day_night_shift,@record_acc,@record_name,@handle_acc,@handle_name,@is_outed," +
                "@product_line,@fixure_id,@log_time)";
            SqlParameter[] parameters = {
            new SqlParameter("@day_night_shift","day"),
            new SqlParameter("@record_acc", "123"),
            new SqlParameter("@record_name", "张飞"),
            new SqlParameter("@handle_acc", "2"),
            new SqlParameter("@handle_name", "operator"),
            new SqlParameter("@is_outed", 1),
            new SqlParameter("@product_line", "1"),
            new SqlParameter("@fixure_id", "2"),
            new SqlParameter("@log_time", "2019/2/18")
            };
			
            int affectCount = SqlHelper.ExecuteNonQuery(sqlValue, parameters);
            Console.WriteLine("影响行数:"+affectCount);
        }

这里使用了控制台程序进行测试,运行代码的截图如下:
在这里插入图片描述

2.这里使用SQLparameter时要注意一点,在前面定义string类型字符串时,对于数据库中varchar类型的数据不需要再添加单引号!!!这是我在后面的使用中所犯的一个错误。下面给出具体的错误例子代码:

错误代码示例:

        public static void TestUpdateParameter()
        {
            string str = "6;7;8";
            string[] strArray = str.Split(';');
            //下面定义的字符串是错误的,需要将@fixure_id两边的单引号删去,才是正确的写法,这样是执行
            string sqlValue = "update fixure_entity set entity_status_id=2 where fixure_id='@fixure_id'";
            SqlParameter[] parameters =
            {

                new SqlParameter("@fixure_id",strArray[0])
            };
          
                int count= SqlHelper.ExecuteNonQuery(sqlValue, parameters);
                Console.WriteLine(count);
        }

正确代码示例:(将单引号删去)

        public static void TestUpdateParameter()
        {
            string str = "6;7;8";
            string[] strArray = str.Split(';');
            string sqlValue = "update fixure_entity set entity_status_id=2 where fixure_id=@fixure_id";
            SqlParameter[] parameters =
            {

                new SqlParameter("@fixure_id",strArray[0])
            };
                int count= SqlHelper.ExecuteNonQuery(sqlValue, parameters);
                Console.WriteLine(count);
            
        }
3.最后给出一个批量插入多条记录的代码示例(仅供参考,基于第一点的代码)
public static void TestSqlParameter()
        {

            string str = "6;7;8";
            string[] strArray = str.Split(';');


            string sqlValue = "insert into out_in_storage(day_night_shift,record_acc," +
                "record_name,handle_acc,handle_name,is_outed,product_line,fixure_id,log_time) " +
                "values(@day_night_shift,@record_acc,@record_name,@handle_acc,@handle_name,@is_outed," +
                "@product_line,@fixure_id,@log_time)";
            SqlParameter[] parameters = {
            new SqlParameter("@day_night_shift","day"),
            new SqlParameter("@record_acc", "123"),
            new SqlParameter("@record_name", "张飞"),
            new SqlParameter("@handle_acc", "2"),
            new SqlParameter("@handle_name", "operator"),
            new SqlParameter("@is_outed", 1),
            new SqlParameter("@product_line", "1"),
            new SqlParameter("@fixure_id", "1"),
            new SqlParameter("@log_time", "2019/2/18")
            };
            int affectCount = 0;
            int totalCount = 0;
            for (int i = 0; i < strArray.Length; i++)
            {
                parameters[7] = new SqlParameter("@fixure_id", strArray[i]);
                affectCount = SqlHelper.ExecuteNonQuery(sqlValue, parameters);
                totalCount += affectCount;
            }

            Console.WriteLine("影响行数:" + totalCount);

        }
4.SQLparameter使用时还有一个注意点:SqlParameter如果传入0会变成NULL

错误测试代码:

SqlParameter parm = new SqlParameter("@id",0);

调试时候发现@id值变成null,无法正确调用。

正确写法:

SqlParameter parm = new SqlParameter("@id",Convert.ToInt32(0));

微软官方解释:
在这里插入图片描述
微软官方的参考文档:
SqlParameter 构造函数

  • 9
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值