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();
}
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With