小编典典

如何在MSSQL上修复“无效列名” SQL异常

sql

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

“无效的列名”

例外。代码如下:

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();

阅读 263

收藏
2021-04-14

共1个答案

小编典典

您在这里错过了单引号" + isim + ",应该是'" + isim + "'。但是,您应始终使用参数化查询来避免SQL注入并摆脱此类错误。

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;
2021-04-14