如何在一段时间内将 'NULL' 个单词分配给文本框(如果文本框为空)?

How to assign 'NULL' word to a text box (if the textbox is empty) during time?

我在从尝试插入的 C# 工具执行 SQL 查询时遇到问题。

如果字符串为空(用户未输入),我需要插入 NULL 值。我尝试使用 DB 空值和普通字符串 'NULL' 进行 NULL 插入,但我得到的只是一个空值(NULL 关键字的 insetead),这给了我错误。

如果有人对此有解决方案,请告诉我....

下面是我的代码

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 Injection

    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.");