我想從C#的winform文本框的數值數據庫字段中插入NULL值。我正在創建一個應用程序,將生產數據輸入到數據庫中。數量變量設置爲int?接受零值,因爲如果一件設備坐下來就沒有價值。數據庫字段也有一個默認值設置爲空。我將如何能夠將文本框留空並在數據庫字段中輸入Null?我已經縮小了我的代碼以包含受影響的內容。如何將int 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());
}
}
'runQty.HasValue'沒有意義,因爲您還沒有給runQty一個值。在這一點上它總是0。它應該是'!String.IsNullOrEmpty(this.runQuatity.Text)'。另一個IF – Rob
https://social.msdn.microsoft.com/Forums/zh-CN/30df6f92-5f8b-483a-b534-132e78bdff48/how-to-set-oledb-parameter-to-null?forum = vblanguage說將該值設置爲'DBNull.Value'。 – Quantic
Convert.ToInt16()是你的問題所在。它將通過設計將null轉換爲0。您需要檢查runQuantity.Text是否爲空,然後將DBNull設置爲參數值。 – Harsh