Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ExecuteScalar需要一个开放且可用的连接。连接的当前状态为关闭_C#_Localdb_Executescalar - Fatal编程技术网

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

C# ExecuteScalar需要一个开放且可用的连接。连接的当前状态为关闭,c#,localdb,executescalar,C#,Localdb,Executescalar,当试图通过LocalDB在我的程序中注册新帐户时,我收到一个错误,说明: ExecuteOnQuery需要打开且可用的连接。连接的当前状态为关闭 但正如你所看到的,我已经打开了连接 我已经尝试在多个位置设置连接字符串,但没有效果 // The methods which will be called if the user tries to log in or register private void LoginRegisterClick(object sender, Ev

当试图通过LocalDB在我的程序中注册新帐户时,我收到一个错误,说明:

ExecuteOnQuery需要打开且可用的连接。连接的当前状态为关闭

但正如你所看到的,我已经打开了连接

我已经尝试在多个位置设置连接字符串,但没有效果


// The  methods which 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]

                                // (cmdCNL) Creates a new record in the LoginsTable
                                SqlCommand cmdCNL = new SqlCommand(@"INSERT INTO LoginsTable (Login, Password) VALUES (@login, @password)", Helper.ConnectionToDB());
                                Helper.ConnectionToDB().Open();
                                cmdCNL.Parameters.AddWithValue("@login", details[6]);
                                cmdCNL.Parameters.AddWithValue("@password", details[7]);
                                cmdCNL.ExecuteNonQuery();

                                // (cmdFindUserID) Finds the UserID of the new acccount which was just created above.
                                SqlCommand cmdFUID = new SqlCommand(@"SELECT * FROM LoginsTable WHERE Login = @login", Helper.ConnectionToDB());
                                cmdFUID.Parameters.AddWithValue("@login", details[6]);
                                var da = new SqlDataAdapter(cmdFUID);
                                var dt = new DataTable();
                                da.Fill(dt);
                                globalVariables.userIDSelected = dt.Rows[0]["UserID"].ToString();

                                // (cmdInsertMainParentTable) Adds to the MainParentTable, a new parent using the UserID from the code above.
                                SqlCommand cmdIMPT = new SqlCommand(@"INSERT INTO MainParentTable (UserID, FirstName, Surname, DOB, Address, HomeTelephone, MobileTelephone, Email) VALUES (@userid, @firstname, @surname, @dob, @address, @hometelephone, @mobiletelephone, @email)", globalVariables.conDB);
                                cmdIMPT.Parameters.AddWithValue("@userid", globalVariables.userIDSelected);
                                cmdIMPT.Parameters.AddWithValue("@firstname", details[0]);
                                cmdIMPT.Parameters.AddWithValue("@surname", details[1]);
                                cmdIMPT.Parameters.AddWithValue("@dob", Convert.ToDateTime(details[2]));
                                cmdIMPT.Parameters.AddWithValue("@address", details[5]);
                                cmdIMPT.Parameters.AddWithValue("@hometelephone", details[3]);
                                cmdIMPT.Parameters.AddWithValue("@mobiletelephone", details[4]);
                                cmdIMPT.Parameters.AddWithValue("@email", details[8]);
                                cmdIMPT.ExecuteNonQuery();
                                Helper.ConnectionToDB().Close();
                            }
                            catch (Exception msg2)
                            {
                                MessageBox.Show("Error Message 2: " + msg2);
                            }
                        }
                    }
                    catch (Exception msg)
                    {
                        MessageBox.Show("Error Message: " + msg);
                        throw;
                    }
                   // Helper.ConnectionToDB().Close();



                    // Populates and brings ucLogIn to the front of the form
                    ucLogIn1.PopulateLogins(details[6], details[7]);
                    lblView.Text = "Log In";
                    lblView.Location = new Point(293, 30);
                    ucLogIn1.BringToFront();                    
                }
                return;      
            }

计数应根据查询结果设置为0或1


GlobalVariables.Con就是这么做的

public static SqlConnection conDB = Helper.ConnectionToDB();
我的助手类如下:

public static class Helper
{
    public static SqlConnection ConnectionToDB()
    {
        return new SqlConnection (@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = G:\myDatabase.mdf; Integrated Security = True"); }
    } 
}

该问题是由以下命令中的此行和类似行引起的

SqlCommand cmdCU = new SqlCommand(........, Helper.ConnectionToDB());
我敢打赌,您的Helper.connectionDB每次调用时都会创建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 
}

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

能否显示Helper.connectionDB的代码?并且,不相关,但顺便说一句,AddWithValue为。它在int count=intcmdCU.ExecuteScalar行失败;Con只是做这个==>publicstaticsqlconnection conDB=Helper.ConnectionToDB;我的助手类如下:应创建公共静态类助手{public static SqlConnection connectiondb{return new SqlConnection@Data Source=LocalDB\MSSQLLocalDB;AttachDbFilename=G:\myDatabase.mdf;Integrated Security=True;}}}连接,在尽可能小的范围内使用和处置-通常为使用块。命令和数据读取器对象也是如此。这使得助手比它保存的更麻烦-所有保存为字符串的数据是另一个大的危险信号。此外,在保存到数据库之前,应该对密码进行加密和哈希处理。您应该有问题来添加附加信息,而不是注释。这次我是为你做的。但是下次请记住,自己动手做。谢谢你的这个@Steve。我一直遵循这一点,直到你的指示第8行。当我在那一行的SQL语句后添加'cnn'时,它会指出一个错误,即当前上下文中不存在cnn名称,因此不可能使用cnn。查看我的代码,变量cnn位于SqlCommand行的上下文中。检查是否有可能改变范围的错误分号