string checkstring = @"SELECT Count(*) FROM Items WHERE itemno = @itemno";
string insertstring = @"INSERT INTO Items (itemno, categ, name, quant, price) VALUES (@itemno, @categ, @name, @quant, @price)";
SqlConnection myConnection = new SqlConnection(@"Data
Source=PC80978273;Initial Catalog=NewUsers;Integrated Security=True");
myConnection.Open();
SqlCommand cmdAdd = new SqlCommand(insertstring, myConnection);
SqlCommand cmdCheck = new SqlCommand(checkstring, myConnection);
int result = (int)cmdCheck.ExecuteScalar();
if (result > 0)
{
MessageBox.Show("Item number already exists.");
}
else
{
cmdAdd.ExecuteNonQuery();
MessageBox.Show("Item has been added to the inventory.");
}
cmdAdd.Parameters.AddWithValue("@itemno", txtItemNo.Text);
cmdAdd.Parameters.AddWithValue("@categ", cmbCategory.SelectedItem.ToString());
cmdAdd.Parameters.AddWithValue("@name", txtName.Text);
cmdAdd.Parameters.AddWithValue("@quant", txtQuantity.Text);
cmdAdd.Parameters.AddWithValue("@price", txtPrice.Text);
myConnection.Close();
如何在将数据插入数据库之前检查重复记录(itemno)并添加错误消息? 发送错误代码
“必须声明标量变量”@itemno“
我的代码出了什么问题?
答案 0 :(得分:3)
在执行命令之前,您应该定义命令参数:
SqlCommand cmdAdd = new SqlCommand(insertstring, myConnection);
SqlCommand cmdCheck = new SqlCommand(checkstring, myConnection);
cmdCheck.Parameters.AddWithValue("@itemno", txtItemNo.Text);
cmdAdd.Parameters.AddWithValue("@itemno", txtItemNo.Text);
cmdAdd.Parameters.AddWithValue("@categ", cmbCategory.SelectedItem.ToString());
cmdAdd.Parameters.AddWithValue("@name", txtName.Text);
cmdAdd.Parameters.AddWithValue("@quant", txtQuantity.Text);
cmdAdd.Parameters.AddWithValue("@price", txtPrice.Text);
int result = (int)cmdCheck.ExecuteScalar();
//do other stuff