Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid column name sql error

I am trying to enter data into my database, but it is giving me the following error:

Invalid column name

Here's my code

string connectionString = "Persist Security Info=False;User ID=sa;Password=123;Initial Catalog=AddressBook;Server=Bilal-PC";

using (SqlConnection connection = new SqlConnection(connectionString))
{
  SqlCommand cmd = new SqlCommand();

  cmd.CommandText = "INSERT INTO Data (Name,PhoneNo,Address) VALUES (" + txtName.Text + "," + txtPhone.Text + "," + txtAddress.Text + ");";
  cmd.CommandType = CommandType.Text;
  cmd.Connection = connection;

  connection.Open();
  cmd.ExecuteNonQuery();
}
like image 978
Snake Avatar asked Dec 05 '11 18:12

Snake


2 Answers

You probably need quotes around those string fields, but, you should be using parameterized queries!

cmd.CommandText = "INSERT INTO Data ([Name],PhoneNo,Address) VALUES (@name, @phone, @address)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Connection = connection;

Incidentally, your original query could have been fixed like this (note the single quotes):

"VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";

but this would have made it vulnerable to SQL Injection attacks since a user could type in

'; drop table users; -- 

into one of your textboxes. Or, more mundanely, poor Daniel O'Reilly would break your query every time.

like image 100
Adam Rackis Avatar answered Sep 28 '22 06:09

Adam Rackis


Always try to use parametrized sql query to keep safe from malicious occurrence, so you could rearrange you code as below:

Also make sure that your table has column name matches to Name, PhoneNo ,Address.

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address)");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = connection;
    cmd.Parameters.AddWithValue("@Name", txtName.Text);
    cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
    cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
    connection.Open();
    cmd.ExecuteNonQuery();
}
like image 45
Elias Hossain Avatar answered Sep 28 '22 06:09

Elias Hossain