教您使用SQL参数变量来传递记录值

如果需要防止SQL注入,可以用SQL参数变量来传递记录值,这可以有效的防止SQL注入,下面就将为您介绍此方法,供您参考,希望对您学习SQL变量的使用能够有所启迪。

public int ExecuteNonQuery(string sql,SqlParameter[]paras)
        {
            int res;
            using (cmd = new SqlCommand(sql, Getconn()))
            {
                //cmd.Parameters.Add(new SqlParameter("@textcaname","最真的梦"));
               // cmd.Parameters.AddRange(new SqlParameter[]{
               // new SqlParameter("@textcaname","南宁新闻")
               // });
                cmd.Parameters.AddRange(paras);
                res = cmd.ExecuteNonQuery();
            }

            return res;
        }

代码说明:此方法用来执行传入的带有SQL数组参数变量的SQL语句

public bool insert(string textcaname)
        {
            bool flag = false;
            string sql = "insert into category (caname) values(@textcaname)";
            SqlParameter[] paras = new SqlParameter[]
            {
            new SqlParameter("@textcaname",textcaname)
            };
            int res = sqlhelper.ExecuteNonQuery(sql, paras);

            if (res > 0)
            {
                flag = true;
            }
            return flag;
        }#p#

代码说明:

string sql = "insert into category (caname) values(@textcaname)";
此是带有SQL参数变量的SQL语句
SqlParameter[] paras = new SqlParameter[]
            {
            new SqlParameter("@textcaname",textcaname)
            };
把从文本框输入的记录值赋给数组参数中的SQL变量


运行效果:

 

 

【编辑推荐】

SQL中的指示变量及数组变量

SQL中系统变量的应用实例

详解SQL Server分布式查询

sql中while语句多层循环实例

SQL函数取得系统日期

 

THE END