“ExecuteScalar:连接属性尚未初始化。”

2024-02-19

我是 C# 新手,目前在不调试的情况下运行该程序时遇到一些问题。

这是我的项目的登录页面。我创建了一个基于服务的数据库,我想连接到数据库中表“Table”中的用户名和密码数据。 但是,我遇到了一个问题“ExecuteScalar:连接属性尚未初始化”。当我运行这段代码时。

谁能帮我这个?

    private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = @userid AND Password = @password";
        cmd.Parameters.AddWithValue("@userid", textBox1.Text);
        cmd.Parameters.AddWithValue("@password", textBox2.Text);
        object result = cmd.ExecuteScalar();

        conn.Open();
        string useridlogin = Convert.ToString(result);
        conn.Close();

        if (useridlogin != " ")
        {
            Home_Page homepage = new Home_Page();
            homepage.Show();
        }
        else
        {
            MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
        }
    }

我可以看到您在打开 SQL 数据库连接之前执行了 ExecuteScalar 方法,导致出现错误。

在 ExecuteScalar 方法之前打开连接,就完成了。

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio 2015\Projects\PersonalFinancialSoftware\PersonalFinancialSoftware\Login.mdf;Integrated Security=True");
    conn.Open();
    SqlCommand cmd = new SqlCommand();

    cmd.CommandText = "SELECT COUNT (*) FROM Table where UserID = @userid AND Password = @password";
    cmd.Parameters.AddWithValue("@userid", textBox1.Text);
    cmd.Parameters.AddWithValue("@password", textBox2.Text);
    object result = cmd.ExecuteScalar();

    string useridlogin = Convert.ToString(result);
    conn.Close();

    if (useridlogin != " ")
    {
        Home_Page homepage = new Home_Page();
        homepage.Show();
    }
    else
    {
        MessageBox.Show("Invalid ID or password, please try again!", "Info", MessageBoxButtons.OK);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“ExecuteScalar:连接属性尚未初始化。” 的相关文章

随机推荐