Jump to content

Hi guys can you please help me in my code? 

Here is my code:

 db.Open();
            MySqlCommand SQL1 = new MySqlCommand("Insert Into tblStudent(`IDNo`, `Grade`, `Section`, `LastName`, `FirstName`, `MiddleName`, `Gender`, 					`Address`, `ContactNo`, `Status`) VALUES ('" + getID() + "', '" + comboBox1.Text + "', '" + comboBox2.Text + "', '" + comboBox3.Text + "', '" + 			textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + comboBox4.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "', 			  '1');", db);
            SQL1.ExecuteNonQuery();
            db.Close();
            MessageBox.Show("One Record has been Added.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        

it always says that "The connection is already open". please respond thnk you. :)

Link to comment
https://linustechtips.com/topic/743524-error-in-c/
Share on other sites

Link to post
Share on other sites

means you probably have db.open(); somewhere else in your code.

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
https://linustechtips.com/topic/743524-error-in-c/#findComment-9422411
Share on other sites

Link to post
Share on other sites

It's usually good practice to dispose of any IDisposable objects. In this case, your MySqlConnection and MySqlCommand classes both implement IDisposable.

 

You can either do this manually by calling the Dispose() method, or you can wrap them in using statements like so which automatically calls it for you.

using (var connection = new MySqlConnection(connectionString))
{
    connection.Open();
    
    var query = "... sql query here ...";
    using (var command = new MySqlCommand(query, connection))
    {
        // Add parameters if necessary. 
        // They add protection against Sql Injection (https://en.wikipedia.org/wiki/SQL_injection).
        // Example)
        // command.Parameters.AddWithValue("@param", value);

        command.ExecuteNonQuery();
    }
}

// Forgive any errors with using the MySql classes. I've done this stuff with Sql Server
// but not MySql so I'm only going off a quick google search. If the MySql classes work in the same way, 
// disposing should clean up all the connections for you so it's easier to avoid errors like you're getting.

 

Link to comment
https://linustechtips.com/topic/743524-error-in-c/#findComment-9426905
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×