Click here to Skip to main content
15,744,193 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:

I'm trying to connect to a MYSQLWorkbench DataBase from VB.NET (Visual Studio) using this code:

Imports System.Data
Imports MySql.Data.MySqlClient
Imports MySql.Data

Public Class Form1

    Dim oCon As MySql.Data.MySqlClient.MySqlConnection

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim sProveedor As String

        sProveedor = "server = localhost; database = vikingos_barberia; user id = root; password = **********; port = 3306"
        oCon = New MySqlClient.MySqlConnection(sProveedor)

        MsgBox("Conexion Exitosa!!")

    End Sub
End Class

What I have tried:

I verified several times the parameter without any change.
Updated 30-Apr-23 18:46pm

The code you posted cannot possibly generate that error. The error message refers to converting something retrieved from the database where a field value is DbNull and you're trying to convert that to another type.

The code you posted does not execute a query at all. All you're doing is opening a connection in the Form_Load event.

As a side-note, you should NOT be opening a connection to the database and keeping it open for the lifetime of your app. You should be opening a connection to the database only when you need to execute a query, and closing it as soon as possible.
Share this answer
To add to what Dave says, it's even worse - you open a connection to the DB which can never be used as it is only stored in a local variable, which goes out of scope at the end of the Form.Load event handler.

Since it can't be accessed at all outside the method (in fact all local variables no longer exists when the method ends) the connection you create is completely useless, and just takes up scarce resources on the server.

You should always us a Using block around the creation of any DB objects (Connection, Command, Reader, and Adapter) to automatically close and Dispose them when the block ends:
Using con As New SqlConnection(strConnect)
	Using cmd As New SqlCommand("SELECT iD, description FROM myTable", con)
		Using reader As SqlDataReader = cmd.ExecuteReader()
			While reader.Read()
				Dim id__1 As Integer = CInt(reader("iD"))
				Dim desc As String = DirectCast(reader("description"), String)
				Console.WriteLine("ID: {0}" & vbLf & "    {1}", iD, desc)
			End While
		End Using
	End Using
End Using
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900