如何修复MsSQL

时间:2018-05-30 06:32:15

标签: c# sql sql-server database ado.net

我试图在运行时传递代码中要检查的列名和值。但是我得到了一个:

  

“无效的列名称”

异常。代码如下:

cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi," +
                          "Ucret,Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) VALUES " +
                          "(" + isim + ",'" + soyisim + "','" + telefon + "'," +
                          "'" + oda_sayisi + "','" + kisi_sayisi + "','" + ucret + "'," +
                          "'" + aciklama + "','" + giris_tar + "','" + cikis_tar + "'," +
                          "'" + current_tarih + "')";
cmd.ExecuteNonQuery(); 
con.Close();

1 个答案:

答案 0 :(得分:6)

您在" + isim + "错过了单引号,它应该是'" + isim + "'。但是,您应该始终使用parameterized queries来避免SQL Injection,并且还要摆脱这种错误。

cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi,Ucret" +
                  ",Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) " +
                  "VALUES (@isim, @soyisim , ...)";
cmd.Parameters.AddWithValue("@isim", isim);
cmd.Parameters.AddWithValue("@soyisim", soyisim);
//Other parameters

虽然直接指定类型并使用Value属性比AddWithValue更好:

cmd.Parameters.Add("@isim", SqlDbType.VarChar).Value = isim;

Can we stop using AddWithValue() already?