在数据库中存储空值

编程入门 行业动态 更新时间:2024-10-26 06:31:33
本文介绍了在数据库中存储空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个表格,其中有一些字段名称,姓氏,生日等。有些字段是可选的,即姓氏,生日等。如果用户不填写这些可选字段,我想在数据库中存储空值。我怎么能这样做?在c#windows app

i have a form in which there are some fields name,last name,birthday etc.some fields are optional i-e last name,birthday etc.i want to store null value in database if user don't fill these optional fields.how can i do this?in c# windows app

推荐答案

只需使用参数化查询(就像你应该使用 所有 用户输入以防止SQL注入问题)并传递DBNull.Value: Just use a parameterised query (as you should with all user input to prevent SQL Injection problems) and pass DBNull.Value: using (SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (MyColumn) VALUES (@VAL)", con)) { object val = tbUserInput.Text; if (string.IsNullOrWhiteSpace(tbUserInput.Text)) val = DBNull.Value; cmd.Parameters.AddWithValue("@VAL", val); ... }

正如OriginalGriff所说,还有一件事。不要忘记在设置数据库表模式的列中允许Null值。因此,如果您传递Null值,它可能/不应该引发错误说,它期望值不是null。 默认情况下非primary,non-identity etc列允许null值和主标识,key columsn不允许null。他们总是需要一些价值来工作。 因此,当您使用上述代码时,必须在列中添加null。 Do as OriginalGriff has said, but one more thing. Do not forget to allow the Null values in the column which setting the Database table schema. So that if you're passing a Null value, it might/should not raise an error saying, it was expecting a value not a null. By default non-primary, non-identity etc columns allow the null value and primary identity and key columsn don't allow null. They always require some value to work on. So, when you're using the above code, you must allow null to be added in the column.

更多推荐

在数据库中存储空值

本文发布于:2023-10-25 22:25:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528286.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!