错误:属性连接尚未初始化

时间:2018-02-19 10:57:37

标签: c# sql sql-server

我正在开展一个项目。我使用visual studio express 2012为桌面窗口构建了一个表单,我用c#编程。这是一个我想在按钮事件中使用的函数:

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();

    }

当我通过在TXT_LOGIN和PW_PASSWORD文本框中添加codeAgent和密码来填写表单时,我收到了以下消息:

  

Connexion成立

     

错误:属性连接尚未初始化

现在,在cmd.Connection = cnn;之前放置int resultat = cmd.ExecuteNonQuery();时,visual studio会发送错误:

  

执行错误:'='附近的语法不正确。

我需要你的帮助。

1 个答案:

答案 0 :(得分:0)

space之后缺少Agent

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

这会导致SQL命令select count(*) from Agentwhere...导致此语法错误。

只需添加一个空格即可按预期工作:

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

但您的代码容易受到SQL-Injection的攻击。
你应该阅读parameterized queries