an error keeping popping up in my codes (connection already open)

前端 未结 2 719
天涯浪人
天涯浪人 2021-01-29 10:16

This error keeps popping up!!! An unhandled exception of type \'System.InvalidOperationException\' occurred in MySql.Data.dll

Additional information: The connection is a

相关标签:
2条回答
  • 2021-01-29 10:43

    It looks like you are not closing the connection after executing the query. You only have

    con.Open()
    

    and are not closing the connection after

    cmd.ExecuteNonQuery()
    
    0 讨论(0)
  • 2021-01-29 10:53

    Keep your database objects local to the method where they are used. Then you always know the state of a connection and can be sure they are closed and disposed. Using...End Using blocks do this for you even if there is an error. In this code both the connection and the command are covered by a single Using block. Note the comma at the end of the first Using line.

    You can pass your connection string directly to the constructor of the connection.

    You can pass your command text and the connection directly to the constructor of the command.

    You Update sql command is not correct. You need to tell the server what fields to update. I had to guess at the names of the fields. Check you database for the correct names and adjust the code accordingly.

    Please don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/ and https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ and another one: https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications Here is another https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html

    I had to guess at the datatypes and field size for the .Add method. Check you database for the correct values and adjust the code.

    I converted the text box strings to the proper datatype here in the database code but normally these values would be parsed and converted before they reach this code.

    Private Sub UpdateSale()
        Using con As New MySqlConnection("Your connection string"),
                cmd As New MySqlCommand("update animal_sale set nonab = @NOAB, amount = @Amount, tax = @Tax, total = @Total where species = @Species;", con)
            cmd.Parameters.Add("@Species", MySqlDbType.VarChar, 100).Value = TextBoxSpecies.Text
            cmd.Parameters.Add("@NOAB", MySqlDbType.Int32).Value = CInt(TextBoxNo.Text)
            cmd.Parameters.Add("@Amount", MySqlDbType.Decimal).Value = CDec(TextBoxAmount.Text)
            cmd.Parameters.Add("@Tax", MySqlDbType.Decimal).Value = CDec(TextBoxTax.Text)
            cmd.Parameters.Add("@Total", MySqlDbType.Decimal).Value = CDec(TextBoxTotal.Text)
            con.Open
            cmd.ExecuteNonQuery()
        End Using
    End Sub
    
    0 讨论(0)
提交回复
热议问题