Unhandled exception in Mysql class - mysql

I'm trying to create a vb.net class to manage a MySQL database connection and i have a method Connect wich is suposed to assign the connection string to a mysqlconnection variable but i'm always getting the error:
An unhandled exception of type 'System.NullReferenceException'
occurred in Projecto_Aula.exe Additional information: Object reference
not set to an instance of an object.
DatabaseManager.vb
Imports MySql.Data.MySqlClient
Public Class DatabaseManager
Private connetionString As String = vbNullString
Private sqlReader As MySqlDataReader
Private sqlAdapter As MySqlDataAdapter
Private sqlCommand As MySqlCommand
Private sqlConnection As MySqlConnection
Sub New(ByVal host As String, ByVal user As String, ByVal password As String, Optional ByVal database As String = "requisicoes")
connetionString = "server=" & host & "; uid=" & user & "; pwd=" & password & "; database=" & database
MsgBox(connetionString)
End Sub
Public Sub Connect()
If (sqlConnection.State = ConnectionState.Open) Then ''throws exception when run
MsgBox("Already connected to the database.")
Return
End If
sqlConnection.ConnectionString = connetionString.ToString()
If (connetionString = vbNullString) Then
MsgBox("Invalid Connection String!")
Application.Exit()
End If
Try
sqlConnection.Open()
Catch ex As MySqlException
MsgBox("Error connecting: " & ex.ToString())
Application.Exit()
End Try
End Sub
End Class
MainMenu.vb
Public Class Login
Public databaseManager As New DatabaseManager("localhost", "root", "", "requisicoes")
Private Sub Form1_Load_1(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
databaseManager.Connect() 'throws exception when run
End Sub
End Class

All of these are NOT set (null/Nothing):
Private sqlReader As MySqlDataReader
Private sqlAdapter As MySqlDataAdapter
Private sqlCommand As MySqlCommand
Private sqlConnection As MySqlConnection
You need to create the objects BEFORE you using then:
Me.sqlReader = New MySqlDataReader
Me.sqlAdapter = New MySqlDataAdapter
Me.sqlCommand = New MySqlCommand
Me.sqlConnection = New MySqlConnection
So in the Connect() method create a new MySqlConnection and replace "myConnectionString" with a valid connection string.
Public Sub Connect()
Me.sqlConnection = New MySqlConnection("myConnectionString")
Try
Me.sqlConnection.Open()
MsgBox(Me.sqlConnection.State.ToString())
Catch ex As MySqlException
MsgBox("Error connecting: " & ex.ToString())
Application.Exit()
End Try
End Sub

Change ur following line of code with this mention code
sqlConnection.ConnectionString = connetionString.ToString()
Change to:
sqlConnection.ConnectionString = Convert.ToString(connetionString)

Related

VB.net 'System.Collections.Generic.KeyNotFoundException' exception

Here is my code:
Imports System.IO
Imports MySql.Data.MySqlClient
Public Class F_login
Dim strServer As String = "localhost"
Dim strDB As String = "lab_utilization"
Dim strUser As String = "root"
Dim strPw As String = ""
Dim cs As String = "Server=$($strServer);Port=3306;Database=$($strDB);Uid=$($strUser);Pwd=$($strPw);"
Dim con As New MySqlConnection(cs)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim id As Integer = uid.Text
Dim pswd As New MySqlCommand("Select Password from authentication where id = " & id & "", con)
pswd.ExecuteNonQuery()
Dim mysqladapter As New MySqlDataAdapter(pswd)
Dim dt As New DataTable
mysqladapter.Fill(dt)
dg.DataSource = dt
Dim psd As String = dg.Rows(0).Cells(0).Value
If pswd1.Text = psd Then
Me.Visible = False
F_Main_screen.Show()
Else
MessageBox.Show("Invalid ID or Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
Private Sub F_login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = cs
con.Open()
End Sub
End Class
The following exception occurs on con.Open():
An unhandled exception of type System.Collections.Generic.KeyNotFoundException' occurred in MySql.Data.dll
Additional information: Keyword 'address' not found.
Any assistance will be appreciated, thank you.
I don't think your syntax for string interpolation is correct.
Try changing your connection string to:
`Dim cs As String = "Server=${strServer};Port=3306;Database=${strDB};Uid=${strUser};Pwd=${strPw};"

Reference required to assembly 'System.Data.Common', containing the type 'DBConnection'

I'm making a program in VB with MySQL. For some reason, I got an error where all of my references had a yellow triangle, but I have since fixed that by reinstalling them on NuGet. Now I have 39 errors which I didn't have before, and I haven't edited the code since then.
Here are the errors:
errors
That isn't all of the errors, but the rest are a lot of duplicates. Now here's my form1 code.
Imports MaterialSkin
Imports MySql.Data.MySqlClient
Imports System.Net
Imports System.Text
Imports System.Data
Public Class Form1
Private Sub LoginBtn_Click(sender As Object, e As EventArgs) Handles LoginBtn.Click
Dim address As String
address = "http://ipv4bot.whatismyipaddress.com"
Dim client As WebClient = New WebClient()
Dim reply As String = client.DownloadString(address)
Dim connString As String = "Database=aquarius;Data Source=localhost;User Id=root;Password=asd"
Dim conn As New MySqlConnection(connString)
Dim Query As String
Dim Query2 As String
Dim reader As MySqlDataReader
Try
conn.Open()
Query = "SELECT * FROM login WHERE username = ?UserName AND password = ?Password AND buyer = ?Buyer"
Dim cmd As New MySqlCommand(Query, conn)
cmd.Parameters.Add(New MySqlParameter("?UserName", MaterialSingleLineTextField1.Text))
cmd.Parameters.Add(New MySqlParameter("?Password", MaterialSingleLineTextField2.Text))
cmd.Parameters.Add(New MySqlParameter("?Buyer", "true"))
cmd.Connection = conn
reader = cmd.ExecuteReader
If reader.HasRows() Then
conn.Close()
MessageBox.Show("Thanks for buying Aquarius", "Welcome")
conn.Open()
Query2 = "INSERT INTO logs (ip, user, time) VALUES (?Ip, ?User, ?Time)"
Dim cmd2 As New MySqlCommand(Query2, conn)
cmd2.Parameters.Add(New MySqlParameter("?Ip", reply.ToString))
cmd2.Parameters.Add(New MySqlParameter("?User", Environment.UserName))
cmd2.Parameters.Add(New MySqlParameter("?Time", System.DateTime.Now.ToString()))
cmd2.ExecuteNonQuery()
conn.Close()
Form2.Show()
Me.Close()
Else
MessageBox.Show("Your password is incorrect or you are not whitelisted.", "Sad")
End If
Catch ex As Exception
MessageBox.Show(ex.ToString, "Error")
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim SkinManager As MaterialSkinManager = MaterialSkinManager.Instance
SkinManager.AddFormToManage(Me)
SkinManager.Theme = MaterialSkinManager.Themes.DARK
SkinManager.ColorScheme = New ColorScheme(Primary.LightBlue500, Primary.LightBlue600, Primary.LightBlue700, Accent.LightBlue200, TextShade.WHITE)
End Sub
Private Sub MaterialRaisedButton1_Click(sender As Object, e As EventArgs) Handles MaterialRaisedButton1.Click
Dim connString As String = "Database=aquarius;Data Source=localhost;User Id=root;Password=asd"
Dim conn As New MySqlConnection(connString)
Dim Query As String
Try
conn.Open()
Query = "INSERT INTO login (username, password, buyer) VALUES (?UserName, ?Password, ?Buyer)"
Dim cmd As New MySqlCommand(Query, conn)
cmd.Parameters.Add(New MySqlParameter("?UserName", MaterialSingleLineTextField1.Text))
cmd.Parameters.Add(New MySqlParameter("?Password", MaterialSingleLineTextField2.Text))
cmd.Parameters.Add(New MySqlParameter("?Buyer", "false"))
cmd.Connection = conn
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show("Done!", ":)")
Catch ex As Exception
MessageBox.Show(ex.ToString, "Error")
End Try
End Sub
End Class

Displaying a value obtained from a mysql query into a VB.net textbox

I am trying to display a value I obatain from a COUNT(*) query in a textbox in vb.net but instead of displaying the obtained value it displays the actual query.
Here is my code:
Imports MySql.Data.MySqlClient
Public Class Statistics
Dim conn As MySqlConnection
Dim command As MySqlCommand
Dim query As String
Dim dadapter As New MySqlDataAdapter
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString =
"server=localhost;userid=root;database=librarydatabase"
Dim reader As MySqlDataReader
Try
conn.Open()
query = "SELECT COUNT(*) FROM login where users='" & Username.Text & "'"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
dadapter.SelectCommand = command
If reader.HasRows Then
reader.Read()
takenout.Text = (query)
End If
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
Here is a screenshot of my program:
When trying to fix the code I change it to replace takenout.Text = (query) with takenout.Text = (reader.read()) and deleting the reader.read()) above and dadapter.SelectCommand = command
Here is the changed code:
Imports MySql.Data.MySqlClient
Public Class Statistics
Dim conn As MySqlConnection
Dim command As MySqlCommand
Dim query As String
Dim dadapter As New MySqlDataAdapter
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString =
"server=localhost;userid=root;database=librarydatabase"
Dim reader As MySqlDataReader
Try
conn.Open()
query = "SELECT COUNT(*) FROM login where users='" & Username.Text & "'"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
If reader.HasRows() Then
takenout.Text = (reader.Read())
End If
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
This code doesn't fix the problem but instead displays true in the textbox when the button is pressed no matter whats in the username textbox.
Here is an image of that:
Use command.ExecuteScalar() instead.
Using command.executescalar() fixes the issue.
Here is a copy of the fixed code if anyone else has a similar issue and wants to see a working example.
Public Class Statistics
Dim conn As MySqlConnection
Dim command As MySqlCommand
Dim query As String
Dim dadapter As New MySqlDataAdapter
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString =
"server=localhost;userid=root;database=librarydatabase"
Dim numtakenout As String
Try
conn.Open()
query = "SELECT COUNT(*) FROM login where users='" & Username.Text & "'"
command = New MySqlCommand(query, conn)
numtakenout = Convert.ToString(command.ExecuteScalar())
takenout.Text = numtakenout
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub

check the manual that corresponds to your mariadb server version for the right syntax to use near "user" at line 1

I have a textbox, button, and datagridview in my form. When i click the button, system will grab a table depending on my textbox from the database and show on datagridview.
I getting this error when i click the button. Where am I wrong?
here is my dbconn
Module mod_dbconn
Public conn As MySqlConnection
Public Sub openDB()
Dim dbname As String = scr_sales.btn_dbswitch.Text
Dim server As String = "localhost"
Dim user As String = "root"
Dim password As String = ""
Try
conn = New MySqlConnection
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, user, password, dbname)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
This is my form
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim query As String = "SELECT * FROM '" + TextBox1.Text + "'"
Dim cmd As New MySqlCommand(query, conn)
Dim da As New MySqlDataAdapter(cmd)
Dim dt = New DataTable
Dim cb As MySqlCommandBuilder
cb = New MySqlCommandBuilder(da)
DataGridView1.Refresh()
Try
conn.Open()
da.Fill(dt)
Dim bsource As New BindingSource
bsource.DataSource = dt
Me.DataGridView1.DataSource = bsource
da.Update(dt)
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
You are trying to build a dynamic table select so for the table name you don't need the quotes around the tablename
"SELECT * FROM " + TextBox1.Text + " ;"

how to avoid error: "CommandText property has not been initialized properly"?

database is in the sqlYog,
when i run this program i am getting the error:
CommandText property has not been initialized properly..?
please help me
Imports MySql.Data.MySqlClient
Imports System.Data
Partial Class login
Inherits System.Web.UI.Page
Public dbconn As New MySqlConnection
Public sql As String
Public dbcomm As New MySqlCommand
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dbconn = New MySqlConnection("data source= localhost; user id=root; password=search; database=bookstore;")
dbconn.Open()
dbcomm.Connection = dbconn
End Sub
Protected Sub btn_login_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_login.Click
Try
dbcomm = New MySqlCommand(sql, dbconn)
sql = "select * from bookstore.lib_user where username=#username and password=#password"
dbcomm.Parameters.AddWithValue("#username", txt_username.Text)
dbcomm.Parameters.AddWithValue("#password", txt_password.Text)
Dim dbadpt As New MySqlDataAdapter(dbcomm)
Dim dt As New DataTable()
dbadpt.Fill(dt)
If dt.Rows.Count > 0 Then
MsgBox("login is suceesfull")
Else
Literal1.Text = "invalid login"
End If
Catch ex As Exception
MsgBox("read this error: " + ex.Message)
End Try
End Sub
End Class
Please change the sequence of lines.
First set the query text then call the command constructor.
sql = "select * from bookstore.lib_user where username=#username and password=#password"
dbcomm = New MySqlCommand(sql, dbconn)
As per your code sql is empty when assigning to your MySqlCommand, You need to set the sql value first then assign it to your MySqlCommand object .
sql = "select * from bookstore.lib_user where username=#username and password=#password"
dbcomm = New MySqlCommand(sql, dbconn)