[英]Passing null into a SQL command
I have a class: 我有一堂课:
public class Intlist
{
public int yesFlag{ get; set; }
public int? noFlag { get; set; }
}
I need to update a database table, but sometimes the value is null for the nullable ints. 我需要更新数据库表,但有时可为空的int的值为null。 I am using
我在用
CommandText = @"UPDATE thetable
SET Yes = " + list.yesFlag +
",NoFlag = " + (list.previous == null) ? DBNull.Value : list.previous +
",NextValue = 10"
I'm trying to get it so that if noFlag is null, it enters a null in the database, but I'm getting errors: 我正在尝试获取它,以便如果noFlag为null,则它将在数据库中输入null,但出现错误:
Cannot implicitly convert type 'string' to 'bool'
无法将类型'string'隐式转换为'bool'
and 和
Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'string'
无法确定条件表达式的类型,因为'System.DBNull'和'string'之间没有隐式转换
Sayka was on target. 塞卡(Sayka)射中目标。 Use parameters .
使用参数 。
Not only will you protect your database from sql injection attacks but you can take advantage of .Nets built in functionality to handle these types of issues. 您不仅可以保护数据库免受sql注入攻击,而且可以利用内置的.Nets功能来处理这些类型的问题。
CommandText = @"UPDATE thetable SET Yes = @yesFlag, NoFlag = @noflag, NextValue = 10";
Command.Parameters.AddWithValue("@yesFlag", list.yesFlag);
Command.Parameters.AddWithValue("@noFlag", list.previous);
Using parameters is strongly recommended. 强烈建议使用参数。 But in your case you just enter as 'Null'.
但是在您的情况下,您只需输入“ Null”即可。 It will work.
会的。
CommandText = @"UPDATE thetable SET Yes = " +
list.yesFlag.ToString() + ",NoFlag = " + (list.previous == null
? "NULL" : list.previous) + ",NextValue = 10";
This query will go as it is. 该查询将照原样进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.