Fatal Error Encounter During Command Execution MySQL VB - mysql

ijust finish my code for inserting data using the vb and mySQL but when i run my webpage it seem have an error Fatal Error Encounter During Command Execution . Please help some how to solve it. below is my code.
Imports System.Data.SqlClient
Imports MySql.Data.MySqlClient
Partial Class Request
Inherits System.Web.UI.Page
Dim MessageBox As Object
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
txt1.Focus()
txt2.Focus()
txt3.Focus()
txt4.Focus()
txt5.Focus()
txt6.Focus()
txt7.Focus()
ddl1.Focus()
ddl2.Focus()
ddl3.Focus()
ddl4.Focus()
End Sub
Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
'Create sql connection and fetch data from database based on employee id
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String = ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Try
conn.ConnectionString = strConnectionString
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
End Try
' Dim cr_id As String
' cr_id = "CR004"
Dim iReturn As Boolean
Using SQLConnection As New MySqlConnection(strConnectionString)
Using sqlCommand As New MySqlCommand()
sqlCommand.Connection = SQLConnection
With sqlCommand
.CommandText = "INSERT INTO cr_record(idcr_record,Emplid,Nama,date,DeptDesc,email,change,reasonchange,problem,priority,reasondescription,systemrequest) VALUES (#IDCR,#Emplid,#Nama,#date,#DeptDesc,'#email,#change,#reasonchange,#problem,#priority,#reasondescription,#systemrequest)"
' .CommandTimeout = 5000000
.CommandType = Data.CommandType.Text
.Parameters.AddWithValue("#Emplid", txt1.Text)
.Parameters.AddWithValue("#Nama", TextBox1.Text)
.Parameters.AddWithValue("#date", txt5.Text)
.Parameters.AddWithValue("#DeptDesc", txt2.Text)
.Parameters.AddWithValue("#email", txt4.Text)
.Parameters.AddWithValue("#change", ddl2.Text)
.Parameters.AddWithValue("#reasonchange", txt6.Text)
.Parameters.AddWithValue("#problem", ddl3.Text)
.Parameters.AddWithValue("#priority", rbl1.Text)
.Parameters.AddWithValue("#reasondescription", txt7.Text)
.Parameters.AddWithValue("#systemrequest", ddl4.Text)
End With
Try
SQLConnection.Open()
' sqlCommand.ExecuteNonQuery()
sqlCommand.ExecuteNonQuery()
iReturn = True
MsgBox("Added Successfully")
Catch ex As MySqlException
MsgBox(ex.Message.ToString & Err.Description)
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
Return
End Sub
End Class

you probably forgot to add this parameter #IDCR
.Parameters.AddWithValue("#IDCR", toyourvariable)

Syntax error in your query:
[...snip...]tDesc,'#email,#change,#rea[...snip...]
^---mis-placed quote.
Reserved words:
[...snip...]c,email,change,reasonc[...snip...]
^^^^^^---- quote with backticks: `change`

Solution that i used and it really works.
This error is mostly caused by a MISSING or Incorrectly Spelled Parameter declaration. eg. #FirstName mistakenly spelled for #FirtName.
Make sure that all the parameters that are declared in the sql query are all declared in the AddwithValue Parameter declaration. (It helps to count the query versus the Addwithvalues).
The best solution is for visual studio to provide information about the missing Parameter. Use a Try-Catch block. In the catch block use Messagebox.show(ex.Innerexception.Message) instead of Messagebox.show(ex.message). This will show the exact Parameter that is missing. eg. below
Try
conCommand.Parameters.Addwithvalue("#FirstName", txtFirstName.text)
conCommand.Parameters.Addwithvalue("#MiddleName", txtMiddleName.text)
conCommand.Parameters.Addwithvalue("#LastName", txtLastName.text)
conCommand.Parameters.Addwithvalue("#PhoneNo", txtPhoneno.text)
catch ex as exception
Messagebox.show(ex.innerexception.Message)
End Try
Hope this helps. Its really great that we share our ideas in the world of programming.

Related

How to save Combobox and checkedlistbox into mysql php using vb

i'm using vb 2017. I try to save combobox value and checkedlistbox item into database. The database table only shows "System.Data.DataRowView" for combobox and "System.Windows.Forms.CheckedListBox+ObjectCollection" for checkedlistbox. Can anyone help me? I'm using mysql phpmyadmin for database. This is the codes i'm using below. it show no error. But the selected item value has not show in database table.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "server=localhost;user=root;database=login;port=3306;password=root123;SslMode=none"
Dim conn As MySqlConnection = New MySqlConnection(constr)
Dim result As Integer
'If True Then
Try
conn.Open()
With {}
Dim cmd As MySqlCommand
For Each item In CheckedListBox1.CheckedItems
cmd = New MySqlCommand("INSERT INTO mastersubject(name,subjectpriority) VALUES(#name,#subjectpriority)", conn)
Next
cmd.Parameters.AddWithValue("#name", ComboBox1.SelectedItem.ToString)
cmd.Parameters.AddWithValue("#subjectpriority", CheckedListBox1.Items.ToString())
result = cmd.ExecuteNonQuery()
'conn.Close()
End With
'End If
If result > 0 Then
MsgBox("Record has been saved")
Else
MsgBox("Error!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End If
Catch ex As Exception
Console.WriteLine(ex.ToString())
MsgBox(ex.Message)
Finally
conn.Close()
End Try
End Sub
Comments and Explanations are in line.
Private Sub InsertRecord()
Dim constr As String = "server=localhost;user=root;database=login;port=3306;password=root123;SslMode=none"
'A Using...End Using block will ensure that your data objects
'are closed and disposed event if there is an error
Try
Using conn As MySqlConnection = New MySqlConnection(constr)
'You need the new keyword to create the command
'Pass the sql query string and the connection object to the
'constructor of the command
'Create the command once, only the value of the subjectpriority changes
Using cmd As New MySqlCommand("INSERT INTO mastersubject (name, subjectpriority) VALUES (#name, #subjectpriority);", conn)
cmd.Parameters.AddWithValue("#name", ComboBox1.SelectedItem.ToString)
cmd.Parameters.Add("#subjectpriority")
'Open the connection as late as possible
conn.Open()
For i = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim Result As Integer
'You are not adding a new parameter, just changing its value
cmd.Parameters("#subjecpriority").Value = CheckedListBox1.CheckedItems(i).ToString()
'the command will be executed for each item checked
Result = cmd.ExecuteNonQuery()
If Result > 0 Then
MessageBox.Show("Record has been saved")
Else
MessageBox.Show("Error!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End If
Next
End Using 'Disposes the command
End Using ' closes and disposes the connection
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Could not insert the data using vb.net into Mysql

I am trying to insert data into MySQL using VB.
When I use these textboxes to insert the data the data gets added, but I don't want to enter the text into textboxes but directly add the underlying information just by press of button (update). It is giving a syntax error to check MySQL version. It it a query error? I don't know how to do this. Please help. Here is my code.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Mysqlconn = New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=*****;database=data"
Dim reader As MySqlDataReader
Try
Mysqlconn.Open()
Dim query As String
query = "INSERT INTO 'data'.'etable'('eid','Name','Surname','Age')values('7','Andy','Roddick','35')"
command = New MySqlCommand(query, Mysqlconn)
reader = command.ExecuteReader
MessageBox.Show("Data Saved")
Mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Mysqlconn.Dispose()
End Try
End Sub
End Class
Try this, which fixes some other issues and potential issues as well:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim query As String = "INSERT INTO `data`.`etable`(eid,Name,Surname,Age)" & _
" VALUES (#eid, #Name, #Surname, #Age)"
Using con As New MySqlConnection("server=localhost;userid=DONT_USE_ROOT!;port=85;password=*****;database=data"), _
cmd As New MySqlCommand(query, con)
'Guessing at parameter types/lengths here.
cmd.Parameters.Add("#eid", MySqlDbType.Int32).Value = 7
cmd.Parameters.Add("#Name", MySqlDbType.VarChar, 20).Value = "Andy"
cmd.Parameters.Add("#Surname", MySqlDbType.VarChar, 25).Value = "Roddick"
cmd.Parameters.Add("#Age", MySqlDbType.Int32).Value = 35
conn.Open()
If cmd.ExecuteNonQuery() > 0 Then MessageBox.Show("Data Saved")
End Using
End Sub
Notice I also removed the exception handler. The Dispose() call in your old handler is now no longer needed (the Using block takes care of this), and I tend to advocate handling exceptions at a higher level than where they are thrown... though in this case you're already in the button event. What I really recommend here is moving the database code to it's own class, so this would all be in a separate method in that class. Then you could still have your exception handler here in the button click event, and the only thing in the Try block would be calling that method.
It's also very important to be in the habit of using query parameters for data that goes into sql queries, in order to prevent sql injection attacks. What you had wasn't vulnerable to attack yet, but it didn't lend any confidence that it wouldn't be vulnerable soon.
The correct character to enclose table name and field names is the backtick not the single quote. Use ALT+096 on your numeric keypad to insert it.
query = "INSERT INTO `data`.`etable`(`eid`,`Name`,`Surname`,`Age`) " & _
"values('7','Andy','Roddick','35')"
Said that, check if you database table has the field eid and Age of type varchar. If the fields are numeric (as the name seems to imply) then your query should be changed to
query = "INSERT INTO `data`.`etable`(`eid`,`Name`,`Surname`,`Age`) " & _
"values(7,'Andy','Roddick',35)"
You code also contains some bad practice that need to be removed to avoid future problems
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim query As String
query = "INSERT INTO `data`.`etable`(`eid`,`Name`,`Surname`,`Age`) " & _
"values(7,'Andy','Roddick',35)"
Using Mysqlconn = New MySqlConnection
Using command = New MySqlCommand(query, Mysqlconn)
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=*****;database=data"
Try
Mysqlconn.Open()
Dim rowsAffected = command.ExecuteNonQuery()
if rowsAffected > 0 Then
MessageBox.Show("Data Saved")
End If
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
First enclose all disposable objects in a Using statement to be sure that they are closed and disposed also in case of exceptions then do not use ExecuteReader for INSERT, UPDATE and DELETE queries, instead the correct method to use is ExecuteNonQuery

I got this error for auto _Suggest and error is "Object reference not set an instance of an object "

Public Sub auto_Suggest(ByVal member As String, ByVal table As String, ByVal txt As Object)
Try
dta = New DataTable
'open the connection
conn.Open()
'holds the data in the database
With cmda
.Connection = conn
.CommandText = "select " & member & " from " & table
End With
'''''''''''''''fill data in the table
daa.SelectCommand = cmda
daa.Fill(dta)
''function of autocomplete
Dim r As DataRow
txt.AutoCompleteCustomSource.Clear()
For Each r In dta.Rows
txt.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
''''close the connection
conn.Close()
daa.Dispose()
End Sub
Private Sub Stock_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
'call a public sub
'the job_id is the field of a table , the employees is the name of a table and a textbox is an object
auto_Suggest("ItemName", "stock", TxtItemName)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
First, it's good to employ a "use it and lose it" approach and take advantage of Using blocks to automatically dispose of connections, commands, and readers. See the example below.
Second, please set a breakpoint on the first line after the Try statement and step through your source in the debugger. If the exception is reached, inspect the ex variable and potentially the ex.InnerException (if any).
Last, the example here uses SQLConnection and SQLCommand (SQL Server). Just swap out whatever library you are using for MySQL and you should be good to go.
Public Sub auto_Suggest(connectionString As String, member As String, table As String, txt As TextBox)
Try
txt.AutoCompleteCustomSource.Clear()
Using cn = New SqlConnection(connectionString)
cn.Open()
Using cmd = New SqlCommand("SELECT " & member & " FROM " & table, cn)
Using dr = cmd.ExecuteReader()
While dr.Read
txt.AutoCompleteCustomSource.Add(dr(member).ToString)
End While
End Using
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

"Object Reference not Set to an Instance of an Object" when trying to read from MySQL

I've been trying to finish up this assignment, due tomorrow, since we got it a few hours ago. Our class was never really taught VB, we just did a brief overview of the very basics of the language and then were told to go copy the code on our assignments and fill in the rest.
At the moment I'm stuck with an error, which you can see in the title, which is preventing me from finishing up the rest of my program. I've looked around for solutions, but they haven't been very helpful due to my complete lack of knowledge of VB and Visual Studio. (I normally code in Java with Eclipse.)
If anyone can explain what's causing this error and how to avoid it in the future that would help a lot. Thanks for any replies.
Imports System.Data
Imports MySql.Data.MySqlClient
Public Class inventoryUpdate_form
Dim quantity As Integer
Dim quantityList As List(Of Integer)
Dim isbn As Integer
Dim isbnList As List(Of Integer)
Public Sub refreshData(first As Boolean)
'Establish connection to the DB.
Dim connection As MySqlConnection = New MySqlConnection
connection.ConnectionString = "server=ERASED;port=ERASED;user id=ERASED;password=ERASED;database=ERASED"
Try
connection.Open()
' Clear the quantity and isbn lists before adding new data.
Try
quantityList.Clear()
Catch e As NullReferenceException
End Try
Try
isbnList.Clear()
Catch e As NullReferenceException
End Try
' Build a query
Dim query As String
query = "SELECT book.title, inventory.quantity, book.ISBN FROM book JOIN inventory ON book.ISBN = inventory.ISBN JOIN store ON inventory.store_id = store.store_id WHERE store.city = 'Fredericton' AND inventory.quantity > 0 ORDER BY book.title ASC"
' Run the query.
Dim cmd As New MySqlCommand(query, connection)
Try
Dim dataReader As MySqlDataReader = cmd.ExecuteReader
Dim title As String
While dataReader.Read()
title = dataReader("title")
ComboBox1.Items.Add(title)
quantity = dataReader("quantity")
quantityList.Add(quantity)
isbn = dataReader("ISBN")
isbnList.Add(isbn)
End While
dataReader.Close()
Catch e As Exception
MessageBox.Show("Data Reader error: " & e.Message)
End Try
Catch e As MySqlException
' If an error occurs while connecting to the DB then show the error message.
MessageBox.Show("Cannot connect to the database: " & e.Message)
Finally
' Close and dispose of the connection to the DB.
connection.Close()
connection.Dispose()
End Try
End Sub
Private Sub inventoryUpdate_form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
refreshData(True)
End Sub
End Class
The error is being shown on this try-catch:
' Run the query.
Dim cmd As New MySqlCommand(query, connection)
Try
Dim dataReader As MySqlDataReader = cmd.ExecuteReader
Dim title As String
While dataReader.Read()
title = dataReader("title")
ComboBox1.Items.Add(title)
quantity = dataReader("quantity")
quantityList.Add(quantity)
isbn = dataReader("ISBN")
isbnList.Add(isbn)
End While
dataReader.Close()
Catch e As Exception
MessageBox.Show("Data Reader error: " & e.Message)
End Try
That's all I know about the error. I've been looking around for some sort of stack trace, but all I've found is this unhelpful block of text which is a bit too messy to paste here so here you go: http://pastebin.com/nGqw6V8R
quantityList and isbnList are null. Use New to initialize them...
Dim quantityList As New List(Of Integer)
Dim isbnList As New List(Of Integer)
I'm not sure but if you are getting a "Object Reference..." error in the try catch block you mention it could be the sibList is not inizialized
Try add in the declaration of the variable this:
Dim isbnList As New List(Of Integer)

VB.Net reuse sql connection

I'm a newbie to vb.net, I'd like to ask is there a way to reuse the sql connection command?
Here is the code for my main.vb:
Dim ServerString As String = "Server=localhost;User Id=root;Password=;Database=pos"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub Main_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
Else
SQLConnection.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Since I'd like to use this in my other classes, i don't want to re-write this code in every form. Any help is truly appreciated. Thanks.
Reusing a connection (or any other unmanaged resource) is normally not a good idea. You should dispose them as soon as possible.
But there's no problem in always creating a new connection anyway, since you're using the ADO.NET connection-pool by default. So you are not creating (and opening) a new physical connection. Actually you're just telling the pool that a conenction is reusable somewhere else now when you close/dispose it. And when you open it, it cannot be used somewhere else, that's why it's important to always close it.
Therefore always use the Using-statement.
Public Shared Function GetColumn1(column2 As Int32) As String
Dim sql = "SELECT Column1 From dbo.tableName WHERE Column2=#Column2 ORDER BY Column1 ASC"
Using con = New SqlConnection(connectionString)
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#Column2", column2)
Try
con.Open()
Using rd = cmd.ExecuteReader()
If rd.Read() Then
Dim Column1 As String = rd.GetString(0)
Return Column1
Else
Return Nothing
End If
End Using
Catch ex As Exception
' log the exception here or do not catch it '
' note that you don't need a Finally to close the connection '
' since a Using-Statement disposes the object even in case of exception(which also closes a connection implicitely)
End Try
End Using
End Using
End Function
Above is a sample method to demontrate that you should not reuse anything.
This is what I normally do: I create a class, e.g. ConnectDB, and a method within this class, e.g. GetConnection. Here is the code:
Imports System.Data
Imports System.Data.SqlClient
Public Class ConnectDB
Public Shared Function GetConnection() As SqlConnection
Dim dbConnString As String = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"
Return New SqlConnection(dbConnString)
End Function
End Class
Then from the method that needs a connection to the database, I call this function. Here is a sample code:
Imports System.Data.SqlClient
Public Class EmployeeDB
Public Shared Function GetEmployees() As List(Of Employee)
Dim con As SqlConnection = ConnectDB.GetConnection()
Dim selectStmt As String = "SELECT * FROM Employees"
Dim selectCmd As New SqlCommand(selectStmt, con)
Dim employees As New List(Of Employee)
Try
con.Open()
Dim reader As SqlDataReader = selectCmd.ExecuteReader()
Do While reader.Read
Dim employee as New Employee
employee.LastName = reader("LastName").ToString
employee.FirstName = reader("FirstName").ToString
...
employees.Add(employee)
Loop
reader.Close()
Catch ex As Exception
Throw ex
Finally
con.Close()
End Try
Return employees
End Function
End Class
You can also modify the selectStmt string to include filter conditions, parameters, and sort order just like Tim's example above and include selectCmd.Parameters.AddWithValue("#<parameterName>", value) for each of your parameters.