C# 如何在一段时间内为文本框(如果文本框为空)分配“空”字?
我在从一个C工具执行SQL查询时遇到了一个问题,该工具试图执行插入操作 如果字符串为空且不是用户输入的,则需要插入NULL值。我尝试使用DB null值和普通字符串'null'来执行null插入,但我得到的只是一个空值instead of null关键字,这给了我错误 如果有人能解决这个问题,请告诉我 下面是我的代码C# 如何在一段时间内为文本框(如果文本框为空)分配“空”字?,c#,.net,winforms,windows-applications,C#,.net,Winforms,Windows Applications,我在从一个C工具执行SQL查询时遇到了一个问题,该工具试图执行插入操作 如果字符串为空且不是用户输入的,则需要插入NULL值。我尝试使用DB null值和普通字符串'null'来执行null插入,但我得到的只是一个空值instead of null关键字,这给了我错误 如果有人能解决这个问题,请告诉我 下面是我的代码 if (comboBox_ConfacValue.Text == "") { comboBox_ConfacValue.Text = DBNull.Value.ToStri
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命令是一种避免灾难的方法。解析错误是常见的错误,但在这种模式背后隐藏着一个更糟糕的敌人,称为
空值必须在插入到表1中的符号中设置。。。值'1',null不是'1','null'。您的插入将产生“1”和“null”。更好的方法是将参数设置为Connection您正在使用的数据库是什么?如果有人键入“;下表1;-了解Sql注入并使用参数我明白了。。。如果我对值使用子查询,那么每个值都需要一个子查询,因此此时我无法使用您建议的内容?@blogprogramisty.net。。。。是的,我知道应该这样使用它,但由于我对每个参数值都使用subquerey,所以我没有其他选择继续使用此方法…如果我需要对参数值使用subquerey怎么办?从服务器上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.");