0

我写了这些代码块:

ConnectDB.getConStr();

         string query = "insert into users (memberName,memberSurname,memberEmail,userName,userPassword) values(@mn,@msn,@me,@un,@up)";
        OleDbCommand cmd = new OleDbCommand( query,ConnectDB.getConStr());
        cmd.Parameters.AddWithValue("@mn", txtName.Text);
        cmd.Parameters.AddWithValue("@msn", txtSurname.Text);
        cmd.Parameters.AddWithValue("@me", txtEmail.Text);
        cmd.Parameters.AddWithValue("@un", txtUsername.Text);
        cmd.Parameters.AddWithValue("@up", txtPassword.Text);

        try
        {
            ConnectDB.getConStr().Open();
            cmd.ExecuteNonQuery();
            ConnectDB.getConStr().Close();
            ltrMesaj.Text = "Record has been added";
            Response.Redirect("Login.aspx");
        }
        catch (Exception ex)
        {
            ltrMesaj.Text = ex.Message;
        }

但我收到这样的错误:ExecuteNonQuery 需要一个打开且可用的连接。连接的当前状态为关闭。

我该如何克服这个问题?

4

1 回答 1

0

每次访问它时,您都在创建新instances的。connection所以只创建一个instance并像这样使用它

    OleDbConnection connection= ConnectDB.getConStr();
    string query = "insert into users (memberName,memberSurname,memberEmail,userName,userPassword) values(@mn,@msn,@me,@un,@up)";
        OleDbCommand cmd = new OleDbCommand( query,connection);
        cmd.Parameters.AddWithValue("@mn", txtName.Text);
        cmd.Parameters.AddWithValue("@msn", txtSurname.Text);
        cmd.Parameters.AddWithValue("@me", txtEmail.Text);
        cmd.Parameters.AddWithValue("@un", txtUsername.Text);
        cmd.Parameters.AddWithValue("@up", txtPassword.Text);

        try
        {
            connection.Open();
            cmd.ExecuteNonQuery();
            connection.Close();
            ltrMesaj.Text = "Record has been added";
            Response.Redirect("Login.aspx");
        }
        catch (Exception ex)
        {
            ltrMesaj.Text = ex.Message;
        }
于 2013-04-14T19:06:58.370 回答