如何分配';NULL';在时间内将单词添加到文本框(如果文本框为空)
本文关键字:文本 添加 单词 如果 分配 何分配 NULL 时间 | 更新日期: 2024-09-24 14:14:41
我在从C#工具执行SQL查询时遇到问题,该工具试图在其中执行插入操作。
如果字符串为空(不是用户输入的),我需要插入NULL值。我尝试使用DB null值和普通字符串"null"来插入null,但我得到的只是一个空值(代替null关键字),这给了我错误。
如果有人对此有解决方案,请告诉我。。。。
下面是我的代码
if (comboBox_ConfacValue.Text == "")
{
comboBox_ConfacValue.Text = DBNull.Value.ToString();
}
if (combobox_conversionDescription.Text == "")
{
combobox_conversionDescription.Text = "NULL";
}
try
{
con.Open();
if (MessageBox.Show("Do you really want to Insert these values?", "Confirm Insert", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
SqlDataAdapter SDA = new SqlDataAdapter(@" insert INTO Table1 (alpha1,alpha2,alpha3) VALUES ('" + comboBox_ConfacValue.Text + "','" + combobox_conversionDescription.Text + "','"+ combobox_Description.Text + "',')",con)
SDA.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Inserted successfully.");
}
}
您应该避免此类代码。连接字符串以生成sql命令会导致灾难。解析错误是常见的错误,但更糟糕的敌人潜伏在这种模式背后,称为Sql注入
try
{
con.Open();
if (MessageBox.Show("Do you really want to Insert these values?", "Confirm Insert", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Now the command text is no more built from pieces of
// of user input and it is a lot more clear
SqlCommand cmd = new SqlCommand(@"insert INTO Table1
(alpha1,alpha2,alpha3)
VALUES (@a1, @a2, @a3)", con);
// For every parameter placeholder add the respective parameter
// and set the DbNull.Value when you need it
cmd.Parameters.Add("@a1", SqlDbType.NVarChar).Value =
string.IsNullOrEmpty(comboBox_ConfacValue.Text) ?
DbNull.Value : comboBox_ConfacValue.Text);
cmd.Parameters.Add("@a2", SqlDbType.NVarChar).Value =
string.IsNullOrEmpty(combobox_conversionDescription.Text ) ?
DbNull.Value : combobox_conversionDescription.Text );
cmd.Parameters.Add("@a3", SqlDbType.NVarChar).Value =
string.IsNullOrEmpty(combobox_Description.Text ) ?
DbNull.Value : combobox_Description.Text );
// Run the command, no need to use all the infrastructure of
// an SqlDataAdapter here....
int rows = cmd.ExecuteNonQuery();
// Check the number of rows added before message...
if(rows > 0) MessageBox.Show("Inserted Successfully.");