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

当尝试通过 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


慕沐林林
浏览 103回答 1
1回答

RISEBY

问题是由这一行(以及以下命令中的类似行)引起的SqlCommand cmdCU = new SqlCommand(........, Helper.ConnectionToDB());我敢打赌,每次调用Helper.ConnectionToDB 时都会创建 SqlConnection 对象的新实例。现在,即使你有这条线&nbsp; Helper.ConnectionToDB().Open();您正在打开一个连接实例,但是由于该命令再次调用Helper.ConnectionToDB,您在每个命令中获得了一个不同的实例并在仍然关闭时使用它。你需要一种完全不同的方法.... previous stuff....if (ucRegister1.AllFieldsValidated() == true){&nbsp; &nbsp; string[] details = ucRegister1.ReturnRegisterDetails();&nbsp; &nbsp; using(SqlConnection cnn = Helper.ConnectionToDB())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; cnn.Open();&nbsp; &nbsp; &nbsp; &nbsp; SqlCommand cmdCU = new SqlCommand("......", cnn);&nbsp; &nbsp; &nbsp; &nbsp; .... replace all calls to Helper.ConnectionDB with the cnn variable ....&nbsp; &nbsp; &nbsp; &nbsp; .....&nbsp; &nbsp; }&nbsp; // <== This close the connection&nbsp;}using 语句可帮助您控制 SqlConnection 及其使用的资源。SqlConnection 是一个一次性对象,重要的非托管资源链接到它。尽快释放这些资源非常重要,using 语句保证当代码退出 using 块时,SqlConnection 将被关闭并释放资源。
打开App,查看更多内容
随时随地看视频慕课网APP