Home > Mobile >  Object reference not set to an instance of an object Mysql VB.net
Object reference not set to an instance of an object Mysql VB.net

Time:10-19

I'm trying to join tables and load data with a specific value from a Textbox but It's giving the following error: "An exception of type 'System.NullReferenceException' occurred in Boxing.exe but was not handled in user code

Additional information: Object reference not set to an instance of an object."

My code:

 Dim Joinloin As New MySqlCommand("SELECT boxno, specie, netweight, producttype, loin FROM loins, boxing WHERE loins.code = boxing.loin AND type = '" & Label9.text & "' ORDER BY loincode", conn.getConnection)

I tried to run without the "type = '" & Label9.text & "'" and works perfectly.

CodePudding user response:

Because "Type" is a reserved word in SQL, you need to change it in your SQL Database and in your Query to something like "TypeX" and try again.

CodePudding user response:

Connections and Commands need to have their Dispose methods called so they can release unmanaged resources. To do this they should be declared in the method they are are used. Using...End Using blocks handle the declare, and Close/Dispose.

Don not concatenate strings to build sq statements. Always use parameters.

Your join syntax went out with the last milenium. I made wild guesse about which field belonged to which table. Is there really a field called loincode?

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim dt = GetProductData(Label9.Text)
    'Do something with the data table
End Sub

Private Function GetProductData(type As String) As DataTable
    Dim dt As New DataTable
    Using cn As New MySqlConnection("You connection string"),
            cmd As New MySqlCommand("SELECT boxing.boxno, loins.specie, boxing.netweight, loins.producttype, boxing.loin 
                                    FROM boxing
                                    JOIN loins ON boxing.loin = loins.code Where loins.[type] = @Type 
                                    ORDER BY boxing.loincode", cn)
        cmd.Parameters.AddWithValue("@Type", type)
        Using reader = cmd.ExecuteReader
            dt.Load(reader)
        End Using
    End Using
    Return dt
End Function
  • Related