Invalid column name sql error

后端 未结 11 1224
梦毁少年i
梦毁少年i 2020-11-30 03:16

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

Invalid column name

Here\'s my code

<
11条回答
  •  死守一世寂寞
    2020-11-30 04:09

    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.

提交回复
热议问题