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

标签 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());
        }
    }

最佳答案

你可以这样做:

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;

关于c# - 如何将 int NULL 插入数字数据库字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35614227/

相关文章:

c# - PerformanceCounter 报告的 CPU 使用率高于观察到的

c# - 如何获取 JSON 对象 - C#

c# - 如何使用 AutoMapper 将嵌套列表映射到另一个列表

database - Grails:如何在内存数据库中预填充数据并拆除

c# - 如何在 C# 中检查我的互联网是否超时

c# - 在 DataGridView 中禁用编辑

c# - 我如何在 C# 中添加按钮?

PHP/MySQL 格式化 : An example of how this type of data is used?

mysql - 关于数据库建模

c# - 选择项目时如何保持组合框打开