我正在嘗試將新車詳細資訊添加到系統中。我想添加 CarId 的 varchar 值。在 carId 的資料庫型別中是 varchar。
這是我的代碼:
private void btnAddCar_Click(object sender, EventArgs e){
if (txtCarId.Text == "" || txtModel.Text == "" || txtColor.Text == "" || txtFuelType.Text == "" || txtPrice.Text == "")
{
MessageBox.Show("Missing Information");
}
else
{
try
{
Con.Open();
string query = "insert into CAR(CarID,Model,Color,FuelType,Available,Price) values(" txtCarId.Text ",'" txtModel.Text "','" txtColor.Text "','" txtFuelType.Text "','" cmbBoxAvailable.SelectedItem.ToString() "'," txtPrice.Text ")";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
MessageBox.Show("Car Successfully Added");
Con.Close();
populate();
}
catch (Exception myEx)
{
MessageBox.Show(myEx.Message);
}
}
}
但是當我向 CarId 文本框輸入值時,出現例外:“Invalid Column name”,“Letter”附近的語法不正確在此處輸入影像描述
uj5u.com熱心網友回復:
我將嘗試修復您的代碼,并希望它能解決您的問題,或者至少讓您更清楚出了什么問題。這是新代碼:
private void btnAddCar_Click(object sender, EventArgs e)
{
if (txtCarId.Text == "" || txtModel.Text == "" || txtColor.Text == "" || txtFuelType.Text == "" || txtPrice.Text == "")
{
MessageBox.Show("Missing Information");
}
else
{
try
{
using (var con = new SqlConnection(<your connectionstring goes here>)
{
con.Open();
string query = "INSERT INTO CAR(CarID,Model,Color,FuelType,Available,Price) VALUES(@CarID,@Model,@Color,@FuelType,@Available,@Price)";
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("@CarID").Value = txtModel.Text;
cmd.Parameters.Add("@Model").Value = txtModel.Text;
cmd.Parameters.Add("@Color").Value = txtColor.Text;
cmd.Parameters.Add("@FuelType").Value = txtFuelType.Text;
cmd.Parameters.Add("@Available").Value = cmbBoxAvailable.SelectedItem.ToString();
cmd.Parameters.Add("@Price").Value = txtPrice.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("Car Successfully Added");
}
populate();
}
}
catch (Exception myEx)
{
MessageBox.Show(myEx.Message);
}
}
}
因此,SqlConnection 現在是本地的,并且包裝在 using 模式中,因此它將被關閉并自動釋放。SqlCommand 也是如此。
該查詢使用引數,因此可以防止 Sql Injection,您不必考慮資料庫型別。這并不完全正確,因為我假設所有資料庫欄位都是字串,這是極不可能的,但您沒有另外指定。不是字串的欄位,您必須在設定引數值之前轉換為正確的型別。
在現實生活中,您會將所有資料庫內容放在資料層中,并且僅在此處處理用戶界面,但我將其留給您自己解決。
此外,您不應該捕獲例外,而是可能發生的例外子型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/479846.html
