插入数据并检查重复记录

时间:2016-11-15 06:55:49

标签: c# sql-server

            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“

我的代码出了什么问题?

1 个答案:

答案 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