我试图在运行时在代码中同时传递列名和要检查的值。但是我得到了:
“无效的列名”
例外。代码如下:
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();
您在这里错过了单引号" + isim + ",应该是'" + isim + "'。但是,您应始终使用参数化查询来避免SQL注入并摆脱此类错误。
" + isim + "
'" + isim + "'
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:
Value
AddWithValue
cmd.Parameters.Add("@isim", SqlDbType.VarChar).Value = isim;