好的,我在這個方面很難,我花了幾天的時間與谷歌等試圖找出我搞砸了。必須聲明標量變量?
我對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