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

瘦欲@ 提交于 2019-12-13 04:38:25

问题


I am trying to insert 1 or 0 in my SQL Server Database, and my data type is "bit". 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?


回答1:


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.

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()+"'");

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.

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

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.




回答2:


Let's see:

  1. Your C# code sample won't even compile.
  2. Your constructing dynamic sql that is susceptible to a SQL injection attack
  3. Your SQL insert query is syntactically invalid and would throw an error if you got your code to compile.

Assuming that those are corrected, the CLR maps SQL Server's bit datatype to/from bool (aka 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 ;
}



回答3:


Inserting bit value in the database table from the c#:

Use sql parameter like this:

SqlParameter = new SqlParameter("@check1", Convert.ToBoolean(0))



来源:https://stackoverflow.com/questions/22155483/how-to-insert-1-or-0-in-sql-server-for-bit-type-field-if-checkbox-is-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!