好的,我在这个方面很难,我花了几天的时间与谷歌等试图找出我搞砸了。必须声明标量变量?
我对C#非常陌生,我正在做的是试图抓住Customer_ID (Primary Key)
从我的SQL Server中,将值1加1,然后输入它作为下一个客户ID。如果我拿出将值添加到Customer_ID
字段的部分,我收到一条错误消息,说我无法插入空值。任何帮助将不胜感激。
的错误是:
必须声明标量变量 “@custID”。
这里是我的代码:
string firstName = fName.Text;
string lastName = lName.Text;
string address1 = address.Text;
string city = addressCity.Text;
string state = addressState.Text;
string zip1 = addressZip.Text;
string phoneNum = phone.Text;
string emailadd = custEmail.Text;
int finalCustID = 0;
SqlCommand getMaxCustID = new SqlCommand("SELECT MAX(Customer_ID) FROM dbo.Customers", Form1.sqlConnection);
getMaxCustID.Parameters.AddWithValue("@custID", finalCustID);
Int32 count = Convert.ToInt32(getMaxCustID.ExecuteScalar());
finalCustID = (int)count + 1;
//Int32 newCustID = count + 1;
SqlCommand saveRecord = new SqlCommand("INSERT INTO dbo.Customers (Customer_ID,First_Name, Last_Name, Customer_Address,City,St,Zip,Phone,Email)" + "Values (@custID'firstName','lastName','address1','city','state','zip1','phoneNum','emailadd')", Form1.sqlConnection);
Console.Write(" This is the final ID " + finalCustID + " \n");
try
{
saveRecord.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Write(saveRecord);
}
这里是我结束了。我不认为这是最好的,但它工作正常。感谢所有帮助:
string firstName = fName.Text;
string lastName = lName.Text;
string address1 = address.Text;
string city = addressCity.Text;
string state = addressState.Text;
string zip1 = addressZip.Text;
string phoneNum = phone.Text;
string emailadd = custEmail.Text;
int finalCustID = 0;
SqlCommand getMaxCustID = new SqlCommand("SELECT MAX(Customer_ID) FROM dbo.Customers", Form1.sqlConnection);
//getMaxCustID.Parameters.AddWithValue("@custID", finalCustID);
Int32 count = Convert.ToInt32(getMaxCustID.ExecuteScalar());
finalCustID = (int)count + 1;
//Int32 newCustID = count + 1;
SqlCommand saveRecord = new SqlCommand("INSERT INTO dbo.Customers " + "(Customer_ID,First_Name, Last_Name, Customer_Address,City,St,Zip,Phone,Email)" + " Values (@custID,@fName,@lName,@address,@city,@state," + "@zip,@phoneNumber,@custEmail)", Form1.sqlConnection); ;
Console.Write(" This is the final ID " + finalCustID + " \n");
try
{
saveRecord.Parameters.AddWithValue("@custID", finalCustID);
saveRecord.Parameters.AddWithValue("@fName", firstName);
saveRecord.Parameters.AddWithValue("@lName", lastName);
saveRecord.Parameters.AddWithValue("@address", address1);
saveRecord.Parameters.AddWithValue("@city", city);
saveRecord.Parameters.AddWithValue("@state", city);
saveRecord.Parameters.AddWithValue("@zip", zip1);
saveRecord.Parameters.AddWithValue("@phoneNumber", phoneNum);
saveRecord.Parameters.AddWithValue("@custEmail", emailadd);
saveRecord.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.Write(saveRecord);
}
@Steve我假设你的意思是说,这是不是一个好方法。我会同意这100%。 josh - 这种类型的方法的问题是,当有多个人同时执行此代码并且他们都获得相同的值时,您会因某些并发问题而导致主键违规。要么使用一个身份,要么你是sql 2012+,你可以使用一个序列。 –
只有当你没有多用户场景时它才能正常工作 – Steve