错误“连接未关闭。连接的当前状态为打开”

时间:2020-06-04 09:51:16

标签: c#

public partial class FormSignup : Form
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\USER\source\repos\ProjectV2\ProjectV2\Account.mdf;Integrated Security=True");
    SqlCommand cmd;
    int ID = 0;
    public FormSignup()
    {
        InitializeComponent();
    }

    private void btnSignup_Click(object sender, EventArgs e)
    {
        con.Open();
        cmd = new SqlCommand("select * from Account where Name='" + txtName.Text + "' and Password ='" + txtPassword.Text + "'", con);
        SqlDataReader rd = cmd.ExecuteReader();
        if (rd.HasRows)
        {
            MessageBox.Show("A account with this Name has been registered. Please try select another username.");
            con.Close();
            ClearData();
            return;
        }
        if (txtPassword.Text != txtRetypePassword.Text)
        {
            MessageBox.Show("Please re-enter password.");
            con.Close();
            ClearData();
            return;
        }
        if (txtName.Text != "" && txtPassword.Text != "" && txtContactNumber.Text != "" && txtAddress.Text != "")
        {
            cmd = new SqlCommand("insert into Account(Name,Password,ContactNumber,Address) values(@name,@password,@contactnumber,@address)", con);
            con.Open();
            cmd.Parameters.AddWithValue("@name", txtName.Text);
            cmd.Parameters.AddWithValue("@password", txtPassword.Text);
            cmd.Parameters.AddWithValue("@contactnumber", txtContactNumber.Text);
            cmd.Parameters.AddWithValue("@address", txtAddress.Text);
            con.Close();
            cmd.ExecuteNonQuery();
            MessageBox.Show("Record Inserted Successfully");
            ClearData();
        }
        else
        {
            MessageBox.Show("Please Provide All Deatails!");
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试一下:

private void btnSignup_Click(object sender, EventArgs e)
    {
        using (con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\USER\source\repos\ProjectV2\ProjectV2\Account.mdf;Integrated Security=True")
        {
          con.Open();
          ...
        }
    }