I am struggling to get this function working as it keeps flagging a syntax error within the INSERT INTO
statement however the same code works on another page / form... can anyone help me out?
It seems to have this issue on another form now too however I can't see what is wrong with it...
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();
}
}
}
When your column names contains spaces you need to encapsulate them between square brackets to avoid confusing the database parser
cmds.CommandText = @"Insert into Assign ([Location ID], [Assign ID],
[Staff ID], SKU) VALUES (@LocID, @AssID, @StaID, @Sku)";
I also suggest to avoid using AddWithValue
because it could have unexpected side effects See Can we stop using AddWithValue already?
For example: I suppose that Location ID is a numeric field (probably an integer). AddWithValue doesn't know this. It sees a string passed as its parameter value. So the parameter is passed as a string. The Database engine need to convert it back to the type expected by the field and this conversion could be done correctly (as probably happens with a simple conversion from a string containing only digits to an integer) or could produce an invalid value as it happens a lot with DateTime values.
It is better to be explicit
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中,如果列/表/ ...名称包含空格或其他特殊字符,则必须将其放在方括号中。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.