本文介绍了如何解决“无效的列名” MSSQL上的SQL异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在运行时在代码中同时传递列名和要检查的值。但是我得到一个:
I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an:
异常。代码如下:
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 +'
。但是,您应该始终使用避免,并消除此类错误。
You've missed a single quote here " + isim + "
and it should be '" + isim + "'
. However you should always use parameterized queries to avoid SQL Injection and also to get rid of this kind of errors.
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
更好:
Although specify the type directly and use the Value
property is more better than AddWithValue
:
cmd.Parameters.Add("@isim", SqlDbType.VarChar).Value = isim;
这篇关于如何解决“无效的列名” MSSQL上的SQL异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!