0

I'm working on a project. i've built a form by using visual studio express 2012 for desktop window and i'm programming in c#. here is a function that i want to use in a button event:

void connect()
    {
            //chaine_connexion="Data Source=MILLIONNAIRE-PC\\ITS4_2017;Initial Catalog=TP_ITS4_2017;User ID=sa;Password=***********"
            string chaine = GestionEnquete.Properties.Settings.Default.chaine_connexion;
            SqlConnection cnn = new SqlConnection();
            cnn.ConnectionString = chaine;

            cnn.Open();

            // test the state of the connection
            if (cnn.State == System.Data.ConnectionState.Open)
                MessageBox.Show("Connexion established");
            else
                MessageBox.Show("Connexion not established");

            //déclare an object SqlCommand type
            SqlCommand cmd = new SqlCommand();

            cmd.CommandText = "select count(*) from Agent" +
                "where codeAgent='" + TXT_LOGIN.Text.Trim() + "'" +
                "and motdepasse = '" + PW_PASSWORD.Password + "'";
            //cmd.Connection = cnn;
            int resultat = cmd.ExecuteNonQuery();
            if (resultat > 0)
            {
                MessageBox.Show("the user exist in the database");
                Equipe a = new Equipe();
                a.Show();
                Hide();
            }
            else
                MessageBox.Show("no user");

            cnn.Close();
        
    }

when i fill the form by adding a codeAgent and a password in TXT_LOGIN and PW_PASSWORD textbox, i received these messages:

Connexion established

error: the property connection has not initialized

Now when a put cmd.Connection = cnn; just before int resultat = cmd.ExecuteNonQuery();, visual studio send the error:

Execution error: incorrect syntaxe near '='.

Please i need your help.

Community
  • 1
  • 1
denioR
  • 15
  • 4

1 Answers1

0

There's a missing space after Agent:

cmd.CommandText = "select count(*) from Agent" + ...

This leads to the SQL command select count(*) from Agentwhere... causing this syntax error.

Just add a space and it should work as expected:

cmd.CommandText = "select count(*) from Agent " +

But your code is vulnerable to SQL-Injection.
You should read about parameterized queries.

MatSnow
  • 7,357
  • 3
  • 19
  • 31