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 构造函数

发布了68 篇原创文章 · 获赞 12 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_35077107/article/details/104397249