David Hayter
David Hayter

Reputation: 75

How to fix "Invalid Column Name" SQL Exception on MSSQL

I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an:

"Invalid Column Name "

Exception. The code is as follows :

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

Upvotes: 1

Views: 225

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39946

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

Although specify the type directly and use the Value property is more better than AddWithValue:

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

Can we stop using AddWithValue() already?

Upvotes: 6

Related Questions