[英]How to assign 'NULL' word to a text box (if the textbox is empty) during time?
我在嘗試執行插入操作的 C# 工具中執行 SQL 查詢時遇到問題。
如果字符串為空(不是由用戶輸入),我需要插入 NULL 值。 我嘗試使用 DB 空值和普通字符串 'NULL' 來執行 NULL 插入,但我得到的只是一個空值(插入 NULL 關鍵字),這給了我錯誤。
讓我知道是否有人對此有解決方案......
下面是我的代碼
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 注入
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.");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.