简体   繁体   中英

How to prevent 2 connection open in database?

I try something good code about prevent duplication of entries but I got error about connection. How can I fix this? Here's my code.

        if(label1.Text == "" || label2.Text == "" || label3.Text == "") {
            MessageBox.Show("Please Select Data");
        } else {
            String query = "Select * from Attendance where empIn=@empIn";
            MySqlCommand cmd1 = new MySqlCommand(query, con);
            cmd1.Parameters.AddWithValue("empIn", label2.Text);
            MySqlDataReader dr = cmd1.ExecuteReader();
            if (dr.HasRows) {
                MessageBox.Show("This Person has already IN");
            } else {
                insert();
            }            
        }
    }

    public void insert()
    {
        int i;
        con.Open();
        MySqlCommand cmd = new MySqlCommand("INSERT INTO Attendance (Name,Date,empIn)VALUES(@Name,@Date,@empIn)", con);
        cmd.Parameters.Add("@Name", MySqlDbType.VarChar).Value = label3.Text;
        cmd.Parameters.Add("@Date", MySqlDbType.Date).Value = Convert.ToDateTime(label1.Text);
        cmd.Parameters.Add("@empIn", MySqlDbType.VarChar).Value = label3.Text;
        i = cmd.ExecuteNonQuery();
        if (i > 0) {
            MessageBox.Show("Data Inserted");
            label2.Text = "";
            label3.Text = "";
            label4.Text = "";

        } else {
            MessageBox.Show("Not Deleted");
        }
        con.Close();

you can simply use the "using" state which will create and close the connection automatically

public object getQueryScaller(string sqlQuery)
    {
        object value = null;

        using (SqlConnection conn = new SqlConnection(_connectionString))
        {
            using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
            {
                conn.Open();
                value = cmd.ExecuteScalar();
            }
        }
        return value;
    }

This will Automatically control the connection problem you will have no need to take care of it. just passing the parameter into the function as SQL statement and it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM