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

How to insert int NULL into numeric database field?

我正在尝试使用 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());
        }
    }

你可以这样做:

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;

您可以使用 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;