如何将int NULL插入数值数据库字段?

时间:2016-02-24 22:11:39

标签: c# database winforms nullable

我正在尝试使用C#从winform文本框中将NULL值插入数值数据库字段。我正在创建一个应用程序,将生产数据输入数据库。数量变量设置为int?接受null,因为如果一件设备坐下,就不会有值进入。数据库字段的默认值也设置为Null。如何将文本框留空并在数据库字段中输入Null?我缩小了代码以包含受影响的内容。

private void btnInsert_Click(object sender, EventArgs e)
    {
        int? runQty = 0;
        int? scrapQty = 0;

        try
        {
            dbConn = new OleDbConnection();
            dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + strDataFilePath + ch;
            dbConn.Open();

            sql = "INSERT INTO DailyProduction (runQty, scrapQty)" +
            "Values (@runQty, @scrapQty)";

            dbCmd = new OleDbCommand(sql, dbConn);

            if (runQty.HasValue)
            {
                runQty = Convert.ToInt16(this.runQuatity.Text);
                dbCmd.Parameters.Add("@runQty", OleDbType.Numeric).Value = runQty;
            }
            else
            {
                runQty = null;
                dbCmd.Parameters.Add("@runQty", OleDbType.Numeric).Value = runQty;
            }

            if (scrapQty.HasValue)
            {
                scrapQty = Convert.ToInt16(this.scrapQuantity.Text);
                dbCmd.Parameters.Add("@scrapQty", OleDbType.Numeric).Value = scrapQty;
            }
            else
            {
                scrapQty = null;
                dbCmd.Parameters.Add("@scrapQty", OleDbType.Numeric).Value = scrapQty;
            }

            dbCmd.Connection.Close();
            dbConn.Close();

            MessageBox.Show("Record Entered!");
        }
        catch (Exception err)
        {
            MessageBox.Show("Error: " + err.Message.ToString());
        }
    }

2 个答案:

答案 0 :(得分:2)

你可以这样做:

var runQty = string.IsNullOrEmpty(this.runQuatity.Text)
    ? DBNull.Value
    : Convert.ToInt16(this.runQuatity.Text);
dbCmd.Parameters.Add("@runQty", OleDbType.Numeric).Value = runQty;

var scrapQty = string.IsNullOrEmpty(this.scrapQuantity.Text)
    ? DBNull.Value
    : Convert.ToInt16(this.scrapQuantity.Text);
dbCmd.Parameters.Add("@scrapQty", OleDbType.Numeric).Value = scrapQty;

答案 1 :(得分:1)

您可以使用string.IsNullOrEmpty()string.IsNullOrWhiteSpace()方法检查字符串是空还是空:

if (string.IsNullOrEmpty(textBox1.Text))
{
    ...
}

另外,对于null值,您应该使用DbNull.Value

dbCmd.Parameters.Add("@runQty", OleDbType.Numeric).Value = DbNull.Value;
dbCmd.Parameters.Add("@scrapQty", OleDbType.Numeric).Value = DbNull.Value;