在数据库中存储空值 [英] store null values in database

查看:129
本文介绍了在数据库中存储空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,其中有一些字段名称,姓氏,生日等。有些字段是可选的,即姓氏,生日等。如果用户不填写这些可选字段,我想在数据库中存储空值。我怎么能这样做?在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.


这篇关于在数据库中存储空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆