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

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)

Related

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

EvaluateException was unhandled by user code Cannot find column [year]

i was trying to filter datagridview with a use of a combobox that is populated by values from a database
i'm having below error
EvaluateException was unhandled by user code
Cannot find column [year].
here is my code
Imports MySql.Data.MySqlClient
Public Class ReportTeacher
Dim MySqlConnection As MySqlConnection
Dim dbDataSet As New DataTable
Private Sub ReportTeacher_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server = localhost; port=3307; user id = root; password = 1234; database = mcs;"
Dim SDA As New MySqlDataAdapter
Dim bSource As New BindingSource
Try
MySqlConnection.Open()
Dim query As String
query = "SELECT DISTINCT year FROM mcs.year "
Dim da As New MySqlDataAdapter(query, MySqlConnection)
Dim ds As New DataSet
da.Fill(ds, "mcs.year")
With cmbxyear
.DataSource = ds.Tables("mcs.year")
.DisplayMember = "year"
.ValueMember = "year"
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MySqlConnection.Dispose()
End Try
Try
MySqlConnection.Open()
Dim query As String
query = "select * from mcs.faculties "
Dim Command As New MySqlCommand(query, MySqlConnection)
SDA.SelectCommand = Command
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView1.DataSource = bSource
SDA.Update(dbDataSet)
MySqlConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MySqlConnection.Dispose()
End Try
End Sub
Private Sub cmbxyear_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbxyear.SelectedIndexChanged
Dim DV As New DataView(dbDataSet)
DV.RowFilter = String.Format(" year like '%{0}%' ", cmbxyear.SelectedItem)
DataGridView1.DataSource = DV
End Sub
can you help me???
it is just the position where you will call the values in mcs. year...it is after when you called the values of mcs.student and insert it into datagrid

Deleting a row from MySQL in ListView in Visual Studio 2013

I'm almost done with a trial program where I add, edit and delete stuff from my MySQL database.
But I can't seem to make the delete button to work.
Here's my code for the Delete Button:
If IDNo = Nothing Then
MsgBox("Please choose an item to delete.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully deleted an item.", MsgBoxStyle.Information)
Me.LoadPeople()
End If
The ERROR
http://stivigan.us.to/images/delete_error.jpg
And here's the rest of my Main Form.
Imports MySql.Data.MySqlClient
Public Class frm_main
Public sConnection As New MySqlConnection
Public IDNo As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
End If
LoadPeople()
End Sub
Public Sub LoadPeople()
Dim sqlQuery As String = "SELECT * FROM tbl_adbms_test"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim TABLE As New DataTable
Dim i As Integer
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(TABLE)
End With
list_view_people.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With list_view_people
.Items.Add(TABLE.Rows(i)("IDNo"))
With .Items(.Items.Count - 1).SubItems
.Add(TABLE.Rows(i)("LastName"))
.Add(TABLE.Rows(i)("FirstName"))
End With
End With
Next
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_add.Click
frm_add.ShowDialog()
End Sub
Private Sub btn_modify_Click(sender As Object, e As EventArgs) Handles btn_modify.Click
If IDNo = Nothing Then
MsgBox("Please choose a record to modify.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "SELECT LastName, FirstName FROM tbl_adbms_test WHERE IDNo='" & list_view_people.SelectedItems(0).Text & "'"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
frm_modify.IDNo = list_view_people.SelectedItems(0).Text
frm_modify.LastName = sqlTable.Rows(0)("LastName")
frm_modify.FirstName = sqlTable.Rows(0)("FirstName")
frm_modify.ShowDialog()
End If
End Sub
Private Sub list_view_people_MouseClick(sender As Object, e As MouseEventArgs) Handles list_view_people.MouseClick
IDNo = list_view_people.SelectedItems(0).Text
End Sub
Private Sub btn_delete_Click(sender As Object, e As EventArgs) Handles btn_delete.Click
If IDNo = Nothing Then
MsgBox("Please choose an item to delete.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully deleted an item.", MsgBoxStyle.Information)
Me.LoadPeople()
End If
End Sub
End Class
Add Form
Public Class frm_add
Public sConnection As New MySqlConnection
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
End If
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
sConnection.Open()
End If
Dim sqlQuery As String = "INSERT INTO tbl_adbms_test(IDNo,LastName,FirstName) VALUES(NULL,'" & txt_last_name.Text & "','" & txt_first_name.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("The data was saved.", MsgBoxStyle.Information)
Dispose()
Close()
frm_main.LoadPeople()
End Sub
End Class
Edit Form
Imports MySql.Data.MySqlClient
Public Class frm_modify
Friend IDNo As Integer
Friend LastName As String
Friend FirstName As String
Public sConnection As New MySqlConnection
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txt_last_name.Text = LastName
txt_first_name.Text = FirstName
End Sub
Private Sub btn_update_Click(sender As Object, e As EventArgs) Handles btn_update.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
sConnection.Open()
End If
Dim sqlQuery As String = "UPDATE tbl_adbms_test SET LastName='" & txt_last_name.Text & "', FirstName='" & txt_first_name.Text & "' WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Record updated successfully.", MsgBoxStyle.Information)
Dispose()
Close()
frm_main.LoadPeople()
End Sub
End Class
Thanks in advance. :)
You don't have the connection open before executing the Delete command.
This is a common scenario when you keep a global connection object around in your code.
You gain nothing and there are always situations in which you end with the connection in a wrong state
You could write
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo=#id"
if sConnection.ConnectionState = ConnectionState.Closed Then
sConnection.Open
End If
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.Parameters.AddWithValue("#id", IDNo)
.ExecuteNonQuery()
End With
but I really suggest to remove your usage of the global connection object and replace it with a local MySqlConnection that will be created just when you use it and closed/destroyed after the usage. This is the intended usage of the Using Statement
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo=#id"
Using con = new MySqlConnection(connstring)
Using cmd = new MySqlCommand(sqlQuery, con)
con.Open
With cmd
.Parameters.AddWithValue("#id", IDNo)
.ExecuteNonQuery()
End With
End Using
End Using
Notice also that I have removed the string concatenation in your sqlQuery and used a safer parameterized approach (albeit in this scenario and if the ListView is not editable there are no real risk of sql injection)

Unhandled exception in Mysql class

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)