Search code examples
c#sqlsql-serverconnection

System.Data.SqlClient.SqlException: Invalid column name (Error at line command.ExecuteNonQuery();)


So I am getting that error all the time. Im not sure if the problem is in the SQL-server. This code for inserting the data into the database.

Send help.

I'm getting this message while executing the code

private void registracija_btn_Click(object sender, EventArgs e)                        
{
        string RegistracijaUporabnisko = RegistracijaUporabnisko_txt.Text;
        string RegistracijaGeslo = RegistracijaGeslo_txt.Text;
        string RegistracijaMail = RegistracijaMail_txt.Text;

            try
            {
                string queryReg = "INSERT INTO uporabnik2(uporabnisko_ime, geslo, email) " +
                     "VALUES(" + RegistracijaUporabnisko + ", " + RegistracijaGeslo + ", " + RegistracijaMail + ")";

                using (SqlCommand command = new SqlCommand(queryReg, con))
                {
                    con.Open();
                    command.ExecuteNonQuery();
                    con.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Napaka: " + ex);
            }

    }

Solution

  • Lets look at your code:

          string queryReg = "INSERT INTO uporabnik2(uporabnisko_ime, geslo, email) " +
                 "VALUES(" + RegistracijaUporabnisko + ", " + RegistracijaGeslo + ", " + RegistracijaMail + ")";
    
            using (SqlCommand command = new SqlCommand(queryReg, con))
            {
                con.Open();
                command.ExecuteNonQuery();
                con.Close();
            }
    

    Ok so if RegistracijaUporabnisko has the value Rok, RegistracijaGeslo the value Rok and RegistracijaMail the value Rok@home.. what does your string now look like? well

     string queryReg = "INSERT INTO uporabnik2(uporabnisko_ime, geslo, email) VALUES(Rok,Rok,Rok@home)";
    

    the Rok it would look for then is a field, not a value. Hence it says invalid column.

    So what if you did it a commonly adopted way of

      string queryReg = "INSERT INTO uporabnik2(uporabnisko_ime, geslo, email) VALUES(@RegistracijaUporabnisko ,@RegistracijaGeslo ,@email)";
    
        using (SqlCommand command = new SqlCommand(queryReg, con))
        {
            command.Parameters.AddWithValue("@RegistracijaUporabnisko ", RegistracijaUporabnisko );
            command.Parameters.AddWithValue("@RegistracijaGeslo ", RegistracijaGeslo );
            command.Parameters.AddWithValue("@email", email);
            con.Open();
            command.ExecuteNonQuery();
            con.Close();
        }
    

    What happens now? Well, behind the scenes text is entered with quotes round it, dates are sent in an appropriate format, numbers all that.. handled for you. It protects you from injection so that if I entered a name of "; drop table uporabnik2 you wouldnt find yourself losing the table etc.