如何向数据库中插入null?
您好,我正在尝试根据 gridview datakeys 值在数据库列中插入 null (如果是“”,则将 null 插入数据库) 但是,我在数据库列内出现一个空格“”。
string sbcId = gvTest.DataKeys[gr.RowIndex]["myColumn"].ToString();
insgnp.Parameters.Add(new OleDbParameter("EMPID", (sbcId==""?DBNull.Value.ToString():sbcId)));
Hi I am trying to insert null in a database column depending on a gridview datakeys value (if being "" insert null into database)
However, I am getting a space ' ' inside the database column.
string sbcId = gvTest.DataKeys[gr.RowIndex]["myColumn"].ToString();
insgnp.Parameters.Add(new OleDbParameter("EMPID", (sbcId==""?DBNull.Value.ToString():sbcId)));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您必须重写您的代码:
您拥有的三元 if 语句的问题是它的返回类型必须始终相同,这就是您不能使用它的原因(字符串和 DbNull.Value 不兼容)
You have to rewrite your code:
The problem with the ternary if statement that you have is that its returntype must always be the same, which is why you cannot use it (string and DbNull.Value are not compatible)
使用
DBNull.Value
,而不是DBNull.Value.ToString
。 (对于 .NET 中的其他参数集合类型,仅使用null
也可以,但我不能 100% 确定OleDbParameter
)。至于三级运算符。不要转换为字符串,而是将字符串转换为对象:
Use
DBNull.Value
, notDBNull.Value.ToString
. (With other parameter collection types in .NET just usingnull
would also work, but I'm not 100% sure aboutOleDbParameter
).As for the tertiary operator. Don't cast to string, but cast the string to object:
您需要使用
DBNull.Value
而不是DBNull.Value.ToString()
DBNull.Value.ToString()
is ''该程序给出
< img src="https://i.sstatic.net/goUIs.jpg" alt="替代文本">
You need to use
DBNull.Value
notDBNull.Value.ToString()
DBNull.Value.ToString()
is ''This program gives
尝试下面通过删除 DBNull.Value 之后的 ToString()
Try below by removing ToString() after DBNull.Value
SQLString.Null
应该可以很好地完成这项工作:)SQLString.Null
should do the job just fine :)我更喜欢使用扩展方法来处理而不是多个 if 语句。这允许您考虑 null 或空字符串值。还允许它可重复使用。
然后你可以使用
I prefer to use an extension method to handle instead of multiple if statements. This allows you to account for null or empty string values. Also allows it to be reusable.
Then you could use
如果你在access数据库中插入非字符串值,你可以这样编写插入查询
Insert into tableName (column1,column2) values (NULL,NULL);
但是你想在中插入空值访问中的短文本或长文本字段您可以这样编写插入查询
Insert into tableName (column1, column2)values('','');
If you Insert a non string value in the access database you may write the insert query in this way
Insert into tableName (column1,column2) values (NULL,NULL);
But you want to insert null value in Short Text or Long Text field in access you may write the insert query in this way
Insert into tableName (column1, column2) values('','');
像这样的字符串
现在添加以下行
,然后插入数据库并检查是否有空值,它们是否符合逻辑
your string like that
now add following line
now insert in db and check you have null value their be logical