Snake Snake - 2 months ago 16
C# Question

Insert data into Sql Server database

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

Answer

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