简体   繁体   English

如果选中复选框,如何在SQL Server中为位类型字段插入1或0?

[英]How to insert 1 or 0 in Sql Server for bit type field if checkbox is checked?

I am trying to insert 1 or 0 in my SQL Server Database, and my data type is "bit". 我试图在我的SQL Server数据库中插入1或0,并且我的数据类型是“位”。 I have tried doing this but it says incorrect syntax near where- 我已经尝试过这样做,但是它在哪里说语法不正确-

dt=g1.ExecDB( insert into tbl ("check1,check2,check3") values('"
            + Convert.ToByte(check1.Checked) + "','"
            + Convert.ToByte(check2.Checked) + "','"
            + Convert.ToByte(check3.Checked) + "' ) )
              where loginname = '"+Session["log"].ToString() + "'"
            ) ;

Please Guide me where I am doing wrong? 请引导我我做错了什么?

Adding the name of your checkboxes inside the sql string cannot work, and of course neither calling Convert.ToByte on them. 将复选框的名称添加到sql字符串中是行不通的,当然也不能在它们上调用Convert.ToByte。 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. 但这当然只是数据库的SQL解析器的无效SQL命令。

Instead you should try to resolve your problem creating a valid SQL command from your C# code. 相反,您应该尝试解决通过C#代码创建有效的SQL命令的问题。 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()+"'");

but there is a big problem with the concatenation of Session["log"] . 但是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 . 连接字符串值(可能由用户输入设置)以形成sql命令是一种非常糟糕的做法,因为它容易受到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 我建议将您的ExecDB更改为这样的内容

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();
     }
 }

and call it with 并用

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);

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. 传递给ExecDB的List<SqlParameter>参数是可选的,因此,如果您有任何代码调用ExecDB不需要参数集合,则可以将代码保留为现在。

Let's see: 让我们来看看:

  1. Your C# code sample won't even compile. 您的C#代码示例甚至无法编译。
  2. Your constructing dynamic sql that is susceptible to a SQL injection attack 您构造的容易受到SQL注入攻击的动态sql
  3. Your SQL insert query is syntactically invalid and would throw an error if you got your code to compile. 您的SQL insert查询在语法上无效,如果您要编译代码,则会引发错误。

Assuming that those are corrected, the CLR maps SQL Server's bit datatype to/from bool (aka System.Boolean ). 假定已更正这些错误,CLR会将SQL Server的bit数据类型映射到bool (也称为System.Boolean )。 So... 所以...

Try something like this: 尝试这样的事情:

const string @insertQuery = @"
  insert tbl ( check1 , check2 , check3 )
  select @p1 , @p2 , @p3
  where loginname = @login
  " ;

using ( SqlConnection conn = GetSqlConnection() )
using ( SqlCommand cmd = conn.CreateCommand() )
{

  cmd.CommandText = insertQuery ;
  cmd.CommandType = CommandType.Text;
  cmd.Parameters.AddWithValue( "@p1"    , check1.Checked ) ;
  cmd.Parameters.AddWithValue( "@p2"    , check2.Checked ) ;
  cmd.Parameters.AddWithValue( "@p3"    , check2.Checked ) ;
  cmd.Parameters.AddWithValue( "@login" , (string) Session["log"] ) ;

  conn.Open();
  int rowsAffected = cmd.ExecuteNonQuery() ;
  conn.Close() ;

  bool success ;
  if      ( rowsAffected == 0 ) success = false ;
  else if ( rowsAffected == 1 ) success = true ;
  else throw new InvalidOperationException() ;

  return success ;
}

Inserting bit value in the database table from the c#: 通过c#在数据库表中插入位值:

Use sql parameter like this: 像这样使用sql参数:

SqlParameter = new SqlParameter("@check1", Convert.ToBoolean(0)) SqlParameter =新的SqlParameter(“ @ check1”,Convert.ToBoolean(0))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果选中gridview内的复选框,如何在数据库字段中插入0或1? - How to insert 0 or 1 in a database field if checkbox inside the gridview is checked? 当日期时间选择器复选框未选中 C# 和 SQL SERVER 时,如何在日期时间列中插入数据库 00/00/0000? - how to insert to database 00/00/0000 in datetime column when datetime picker checkbox not checked C# and SQL SERVER? 将复选框模板字段中的值插入sql数据库字段类型中 - Inserting value from Checkbox Template Field into sql database field type Bit 基于GridView中选中的复选框在sqlDatabase的Bit字段中插入1或0 - Inserting 1 or 0 in Bit field in sqlDatabase based on Checkbox checked in GridView 如何使用 c# (latebound) 将来自 SQL Server 的货币数据类型插入到 crm 中的货币字段 - How to insert money data type from SQL server into currency field in crm using c# (latebound) 如何将多个复选框值插入SQL Server数据库 - How to insert multi checkbox value into SQL Server database 如何从数据列表中的复选框将文本和值插入SQL Server - How to insert text and value from checkbox in datalist into sql server 如果选中了复选框,则为必填字段 - Require field if checkbox is checked 如何将 Nullable Bit 类型值传递给 SQL Server 存储过程? - How to pass Nullable Bit type value into to SQL Server stored procedure? 如何将长类型数据插入到SQL SERVER Big int类型 - How to insert long type data in to SQL SERVER Big int type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM