更新时间:2023-02-08 17:27:12
在sql字符串中添加复选框名称是行不通的,当然也不能在它们上调用Convert.ToByte.这样,您可以在字符串内简单插入控件的名称和应该转换其值的函数的名称.但是,对于数据库的SQL解析器,这当然只是无效的SQL命令.
Adding the name of your checkboxes inside the sql string cannot work, and of course neither calling Convert.ToByte on them. In this way you simple insert inside a string the name of your controls and the name of a function that should convert their values. But of course this is only an invalid SQL command for the sql parser of your database.
相反,您应该尝试解决通过C#代码创建有效的SQL命令的问题.这是您问题的初步解决方案
Instead you should try to resolve your problem creating a valid SQL command from your C# code. This is an initial possible solution to your problem
dt=g1.ExecDB("insert into tbl (check1,check2,check3) values(" +
(check1.Checked ? "1" : "0") + ", " +
(check2.Checked ? "1" : "0") + ", " +
(check3.Checked ? "1" : "0") +
") where loginname='"+Session["log"].ToString()+"'");
,但是Session["log"]
的串联存在很大问题.
串联字符串值(可能由用户输入设置)以形成sql命令是非常不好的做法,因为它容易受到
but there is a big problem with the concatenation of Session["log"]
.
Concatenating string values (probably setup by user input) to form a sql command is a very bad practice because it is vulnerable to Sql Injection. So a change to the ExecDB
to receive a list of parameters is mandatory.
我建议将您的ExecDB更改为类似的内容
I suggest to change your ExecDB to something like this
public int ExecDB(string query, List<SqlParameter>parameters = null)
{
using(SqlConnection cn = new SqlConnection(connString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
cn.Open();
if(parameters != null && parameters.Count > 0)
cmd.Parameters.AddRange(parameters.ToArray());
return cmd.ExecuteNonQuery();
}
}
并用
List<SqlParameter> ps = new List<SqlParameter>();
SqlParameter p = new SqlParameter("@login", Session["log"].ToString());
ps.Add(p);
dt=g1.ExecDB("insert into tbl (check1,check2,check3) values(" +
(check1.Checked ? "1" : "0") + ", " +
(check2.Checked ? "1" : "0") + ", " +
(check3.Checked ? "1" : "0") +
") where loginname=@login", ps);
传递给ExecDB的List<SqlParameter>
参数是可选的,因此,如果您有任何代码调用ExecDB不需要参数集合,则可以将代码保留为现在.
the List<SqlParameter>
parameter passed to ExecDB is optional, thus, if you have any code where the call to ExecDB doesn't need a parameter collection you could leave your code as is now.