OleDbConnection连接错误

时间:2013-04-14 19:02:12

标签: asp.net c#-4.0 oledbconnection executenonquery

我写了这些代码块:

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需要一个开放且可用的连接。连接的当前状态已关闭。

我如何克服这个问题?

1 个答案:

答案 0 :(得分: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;
        }