Adel Hawa
Adel Hawa

Reputation: 27

SQL Insert fails with invalid column name

When I try to fill textbox1 with a name, I get an exception indicating an invalid column name. When I fill it with a number it works.

The datatype of coach_name is varchar(50).

The insert code is:

 // connection setup code
    SqlConnection conn = new SqlConnection(connString);
    string Coach_Name = textBox1.Text;
    try {        
    string Password1=textBox2.Text;
    string Password2=textBox3.Text;
    string Password=textBox2.Text;

    if (Password1.Equals(Password2))
    {

        SqlCommand cmd = new SqlCommand("insert into CoachLogins values (" + Coach_Name + ",'" + Password + "')", conn);

        conn.Open();
        cmd.ExecuteNonQuery(); // hyi insert update delete ma btekhod shi

    }        

Upvotes: 0

Views: 223

Answers (2)

Dgan
Dgan

Reputation: 10275

try to turn your code like this:

Point should be Cover

  1. Wrap Your Connection and Command with **using** which Implements IDisposable
  2. Dont Use Plain Password. instead of use Algorithms to encrypt it
  3. Always Use SQLParameters SQL to AVOID SQL INJECTION
using (SqlConnection con=new SqlConnection(MyConnectionString))
{
conn.Open();
using(SqlCommand command= new SqlCommand("insert into 
CoachLogins (Coach_Name,Password )
   values (@Coach_Name , @Password )", conn))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("@Coach_Name", SqlDbType.NVarChar,100).Value = TextBox1.Text;
command.Parameters.Add("@Password", SqlDbType.NVarChar,100).Value = TextBox2.Text;
.....

 cmd.ExecuteNonQuery();

con.dispose


}

}

Upvotes: 0

Tanner
Tanner

Reputation: 22733

You haven't wrapped Coach_Name in quotes, so it won't work if you pass it a string. Numeric values will work in a query like that as they don't have to be wrapped in quotes:

SqlCommand cmd = new SqlCommand _
   ("insert into CoachLogins values ('" + Coach_Name + "','" + Password + "')", conn);

Please read about using parameterised queries & SQL injection.

Also, I know this might be early days in your development work, but name your controls with something more useful than: button1 and textBox1. It will soon become a mess if you carry on down that path.

Upvotes: 4

Related Questions