为了账号安全,请及时绑定邮箱和手机立即绑定

ExecuteScalar 需要一个开放且可用的连接。连接的当前状态是关闭的

ExecuteScalar 需要一个开放且可用的连接。连接的当前状态是关闭的

C#
慕沐林林 2022-12-24 10:02:26
当尝试通过 LocalDB 在我的程序中注册一个新帐户时,我收到一条错误消息:ExecuteNonQuery 需要一个打开且可用的连接。连接的当前状态是关闭的但如您所见,我已经打开了连接我已经尝试在多个地方设置连接字符串但无济于事// The  methods whh will be called if the user tries to log in or register        private void LoginRegisterClick(object sender, EventArgs e)        {            // The following lines of code will execute if the user tries to register            if (lblView.Text == "Register")            {                // If all the textboxes have passed validation, the details from the textboxes are retrieved and stored                if (ucRegister1.AllFieldsValidated() == true)                {                    string[] details = ucRegister1.ReturnRegisterDetails();                    // (cmdCountUsernames) Checks to see if new username is unique                    Helper.ConnectionToDB().Open();                    SqlCommand cmdCU = new SqlCommand(@"SELECT COUNT(*) FROM LoginsTable WHERE Login = '" + details[6] + "'", Helper.ConnectionToDB());                    try                    {                        int count = (int)cmdCU.ExecuteScalar();                        //int count = Convert.ToInt32(cmdCU.ExecuteScalar());                        // If the new username is unique, the record is added into MainParentTable                        if (count == 0)                        {                            try                            {                                // Order of the details:                                         // details[(0)Firstname, (1)Surname, (2)DOB, (3)HomeTel, (4)MobileTel, (5)Address, (6)Username, (7)Password, (8)Email]                            }                            catch (Exception msg2)                            {                                MessageBox.Show("Error Message 2: " + msg2);                            }                        }                    }应根据查询结果将计数设置为 0 或 1
查看完整描述

1 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

问题是由这一行(以及以下命令中的类似行)引起的


SqlCommand cmdCU = new SqlCommand(........, Helper.ConnectionToDB());

我敢打赌,每次调用Helper.ConnectionToDB 时都会创建 SqlConnection 对象的新实例。


现在,即使你有这条线


  Helper.ConnectionToDB().Open();

您正在打开一个连接实例,但是由于该命令再次调用Helper.ConnectionToDB,您在每个命令中获得了一个不同的实例并在仍然关闭时使用它。


你需要一种完全不同的方法


.... previous stuff....

if (ucRegister1.AllFieldsValidated() == true)

{

    string[] details = ucRegister1.ReturnRegisterDetails();

    using(SqlConnection cnn = Helper.ConnectionToDB())

    {

        cnn.Open();

        SqlCommand cmdCU = new SqlCommand("......", cnn);


        .... replace all calls to Helper.ConnectionDB with the cnn variable ....


        .....

    }  // <== This close the connection 

}

using 语句可帮助您控制 SqlConnection 及其使用的资源。SqlConnection 是一个一次性对象,重要的非托管资源链接到它。尽快释放这些资源非常重要,using 语句保证当代码退出 using 块时,SqlConnection 将被关闭并释放资源。


查看完整回答
反对 回复 2022-12-24
  • 1 回答
  • 0 关注
  • 66 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信