[英]Save function in c# windows form not completing due to a syntax error
我正在努力使此函數正常工作,因為它會在INSERT INTO
語句中不斷標記語法錯誤,但是同一代碼可在另一頁/窗體上工作……有人可以幫我嗎?
看來現在也存在其他形式的問題,但是我看不出這是怎么回事...
private void btnAssign_Click(object sender, EventArgs e)
{
string LocID = txtLocID.Text;
string AssID = txtAssID.Text; // declaing instance names
string StaID = txtID.Text;
string Sku = txtSKU.Text;
if (txtLocID.Text.Length < 1) // validating a text box
{
MessageBox.Show("Please Enter an Location ID");
}
else if (txtAssID.Text.Length < 1)
{
MessageBox.Show("Please Enter an Assignment ID");
}
else if (txtID.Text.Length < 1)
{
MessageBox.Show("Please Enter a Staff ID");
}
else if (txtSKU.Text.Length < 1)
{
MessageBox.Show("Please Enter a Product SKU");
}
else
{
try
{
int Loc;
Cons.ConnectionString = ConnectionDetail.Warehouse;
OleDbCommand cmds = new OleDbCommand();
Cons.Open();
cmds.CommandText = @"Insert into Assign (Location ID, Assign ID, Staff ID, SKU) VALUES (@LocID, @AssID, @StaID, @Sku)";
cmds.Connection = Cons;
cmds.Parameters.AddWithValue("LocID", LocID);
cmds.Parameters.AddWithValue("AssID", AssID);
cmds.Parameters.AddWithValue("StaID", StaID);
cmds.Parameters.AddWithValue("Sku", Sku);
Loc = cmds.ExecuteNonQuery();
if (Loc > 0)
MessageBox.Show("Location has successfully been assigned a product and Saved");
}
catch (Exception err)
{
MessageBox.Show("error:" + Environment.NewLine + err.Message);
}
finally
{
if (Cons.State == ConnectionState.Open)
Cons.Close();
}
}
}
當您的列名稱包含空格時,您需要將其封裝在方括號之間,以避免混淆數據庫解析器
cmds.CommandText = @"Insert into Assign ([Location ID], [Assign ID],
[Staff ID], SKU) VALUES (@LocID, @AssID, @StaID, @Sku)";
我還建議避免使用AddWithValue
因為它可能會產生意外的副作用。請參閱我們可以停止使用AddWithValue嗎?
例如:我假設位置ID是一個數字字段(可能是整數)。 AddWithValue不知道這一點。 它看到傳遞的字符串作為其參數值。 因此參數作為字符串傳遞。 數據庫引擎需要將其轉換回字段期望的類型,並且此轉換可以正確完成(可能是從僅包含數字的字符串到整數的簡單轉換而發生的),或者在發生這種情況時可能產生無效值DateTime值很多。
最好是明確的
int locID;
if(!Int32.TryParse(txtLocID.Text, out locID))
MessageBox("Not a valid location number!");
......
cmds.Parameters.Add("LocID", OleDbType.Integer).Value = locID;
INSERT into Assign([Location ID], [Assign ID] ...) values ...
在sql中,如果列/表/ ...名稱包含空格或其他特殊字符,則必須將其放在方括號中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.