Insert语句不会插入Null值 [英] Insert statement won't insert Null value

查看:1317
本文介绍了Insert语句不会插入Null值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图插入一个空值在C#中像这样我的数据库:

I'm trying to insert a null value into my database from C# like this:

SqlCommand command = new SqlCommand("INSERT INTO Employee
VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text
        + "','" + phone.Text + "','" + DBNull.Value + "')", connection);

DBNull.Value就是一个日期可以,但我想它是等于空,但它似乎把一个默认日期1900年什么......

DBNull.Value is where a date can be but I would like it to be equal to null but it seems to put in a default date, 1900 something...

推荐答案

更改为:

SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text + "','" + phone.Text + "',null)", connection);

DBNull.Value.ToString()返回空字符串,但你要null替代。

DBNull.Value.ToString() returns empty string, but you want null instead.

然而,这建立查询可能会导致问题的方式。例如,如果你的一个字符串包含引号'生成的查询将抛出错误。更好的方法是使用参数和SqlCommand对象上设置:

However this way of building your query can lead to issues. For example if one of your strings contain a quote ' the resulting query will throw error. A better way is to use parameters and set on the SqlCommand object:

SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES (@empId,@name,@age,@phone,null)", connection);
command.Parameters.Add(new SqlParameter("@empId", employeeId.Text));
command.Parameters.Add(new SqlParameter("@name", name.Text));
command.Parameters.Add(new SqlParameter("@age", age.Text));
command.Parameters.Add(new SqlParameter("@phone", phone.Text));

这篇关于Insert语句不会插入Null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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