How can I resolve a fatal SQL statement error? - mysql

I was having problems updating information in my SQL database using my vb.net application, but recently I found the solution. However now I have run into another problem which is shown in the code below:
Private Sub cmdupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdupdate.Click
Dim conn As New MySqlConnection
Dim myCommand As New MySqlCommand
'#######
conn.ConnectionString = "server=" & frmLogin.txtserver.Text & ";" _
& "user id=" & frmLogin.txtusername.Text & ";" _
& "password=" & frmLogin.txtpassword.Text & ";" _
& "database=in_out"
'#######
myCommand.Connection = conn
myCommand.CommandText = "UPDATE event SET" _
& "status = ?Status " _
& "WHERE user_id = ?UserID AND message_id = ?MessageID AND creator = ?Creator"
myCommand.Parameters.AddWithValue("?UserID", myUserID)
myCommand.Parameters.AddWithValue("?MessageID", cbomessage.SelectedValue)
myCommand.Parameters.AddWithValue("?Status", cbostatus.SelectedItem)
myCommand.Parameters.AddWithValue("?Creator", myUserID)
myCommand.Connection = conn
Try
myCommand.Connection.Open()
myCommand.ExecuteNonQuery()
myCommand.Connection.Close()
Catch myerror As MySqlException
MsgBox("There was an error updating the database: " & myerror.Message)
End Try
End Sub
The exception message is:
Fatal error encountered during command execution.
I don't know if this is simply a syntax error that can be fixed easily, or something to do with my database configuration.

If I decipher your screen shot correctly, then your UPDATE statement is being put together:
"UPDATE event SET" &
"status = ?Status" &
"WHERE user_id = ....... "
This results in:
UPDATE event SETstatus = ?StatusWHERE user_id = .......
so you're really only missing some spaces!
"UPDATE event SET " & -- observe the SPACE after the SET !
"status = ?Status " & -- observe the SPACE after the ?Status
"WHERE user_id = ....... "

Add space before ; on below
conn.ConnectionString = "server=" & frmLogin.txtserver.Text & ";" _
Thanks

Related

System.Data.OleDb.OleDbException Error while writting query in visual basic

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\BlackHat\Documents\Travel.accdb")
Dim qry As String = "update Login set UserName='" & TextBox1.Text & "',Password='" & TextBox2.Text & "' where ID=" & Val(TextBox3.Text)
Dim cmd As New OleDbCommand(qry, con)
con.Open()
cmd.ExecuteNonQuery()
MsgBox(qry)
con.Close()
End Sub
Following error occurred in the query. the syntax and variable looks fine.
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in UPDATE statement.
Try this:
Dim qry As String ="update Login set UserName='" & TextBox1.Text & "',Password='" & TextBox2.Text & "' where ID=" & Val(TextBox3.Text) & ""

"Fatal error encountered during command execution" I'm using SET and SELECT xxx FROM (SELECT xxx FROM xxx)

I have this code:
Function Get_Control_Station_Address(counter As Integer)
Check_DB_Con() 'Check if the connection is okay
SQL_Query = "SET #row_number = 0; " _
& "SELECT hardware_add " _
& "FROM (" _
& "SELECT " _
& "#row_number:=#row_number + 1 AS num, " _
& "hardware_add AS hardware_add " _
& "FROM teller_info" _
& ") AS sub_query " _
& "WHERE num = " & counter & ";"
Dim MySQL_CMD As New MySqlCommand(SQL_Query, MysqlConn)
Try
MySQL_CMD.Connection.Open()
MySQL_Reader = MySQL_CMD.ExecuteReader()
While MySQL_Reader.Read
MySQL_Result = MySQL_Reader("hardware_add")
End While
Return MySQL_Result
MySQL_Reader.Close()
Catch myerror As MySqlException
Console.WriteLine("Failed to run query: " & myerror.Message)
Return Nothing
Finally
MysqlConn.Close()
MysqlConn.Dispose()
End Try
End Function
I am receiving this error:
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
A first chance exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Failed to run query: Fatal error encountered during command execution.
I am sure that there's no basic errors here like database connection error, as a proof I have this function that I am 100% sure working and it is almost the same to the previous function which is not working, the only difference is the query.
Function Get_Control_Station_Total()
Check_DB_Con() 'Check if the connection is okay
SQL_Query = "SELECT COUNT(*) AS total_count FROM teller_info"
Dim MySQL_CMD As New MySqlCommand(SQL_Query, MysqlConn)
Try
MySQL_CMD.Connection.Open()
MySQL_Reader = MySQL_CMD.ExecuteReader()
While MySQL_Reader.Read
MySQL_Result = MySQL_Reader("total_count")
End While
Return MySQL_Result
MySQL_Reader.Close()
Catch myerror As MySqlException
Return ("Failed to run query: " & myerror.Message)
Finally
MysqlConn.Close()
MysqlConn.Dispose()
End Try
End Function
So looking close at the problem it seems that this code is the root of error.
SQL_Query = "SET #row_number = '0'; " _
& "SELECT hardware_add " _
& "FROM (" _
& "SELECT " _
& "#row_number:=#row_number + 1 AS num, " _
& "hardware_add AS hardware_add " _
& "FROM teller_info" _
& ") AS sub_query " _
& "WHERE num = '" & counter & "';"
Actually I re-create that query directly using heidiSQL and it working great, so I am a little bit stuck here, maybe I am using SET #row_number = '0'; wrong?
In Summary:
I am sure that it is not MySQL connection problem
I am sure that the MySQL query is working (by testing it directly on HeidiSQL)
The process of getting data seems to be working because I just copy the way it gets data from a working function.
Edit: By following #Ken_White's comment of commenting console.writeline I am able to see clearly the error
Here's the error
MySql.Data.MySqlClient.MySqlException (0x80004005): Fatal error encountered during command execution. ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Parameter '#row_number' must be defined.
at MySql.Data.MySqlClient.Statement.SerializeParameter(MySqlParameterCollection parameters, MySqlPacket packet, String parmName, Int32 parameterIndex)
at MySql.Data.MySqlClient.Statement.InternalBindParameters(String sql, MySqlParameterCollection parameters, MySqlPacket packet)
at MySql.Data.MySqlClient.Statement.BindParameters()
at MySql.Data.MySqlClient.PreparableStatement.Execute()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at TCP_Client.Module_Database.Get_Control_Station_Address(Int32 counter) in C:\Users\xxxxx\xxx.vb:line 198
It seems that by adding Allow User Variables = True to my database connection solves my problem.
So instead of
Public Sub Check_DB_Con()
'Declare database credentials so we can refresh it in recheck timer
server = My.Settings.DB_Server
username = My.Settings.DB_Username
password = My.Settings.DB_Password
database = My.Settings.DB_Database
'Connection String
MysqlConn.ConnectionString = "server=" & server & ";" _
& "user id=" & username & ";" _
& "password=" & password & ";" _
& "database=" & database
End Sub
I add Allow User Variables=True, so it will become
Public Sub Check_DB_Con()
'Declare database credentials so we can refresh it in recheck timer
server = My.Settings.DB_Server
username = My.Settings.DB_Username
password = My.Settings.DB_Password
database = My.Settings.DB_Database
'Connection String
MysqlConn.ConnectionString = "server=" & server & ";" _
& "user id=" & username & ";" _
& "password=" & password & ";" _
& "database=" & database & ";Allow User Variables=True"
End Sub
Instead of setting the value of the rn in a 2 step SQL, use a cross join. I don't think the call handles the two statements correctly.
SQL_Query = "SELECT hardware_add " _
& "FROM (" _
& "SELECT " _
& "#row_number:=#row_number + 1 AS num, " _
& "hardware_add AS hardware_add " _
& "FROM teller_info" _
& "CROSS JOIN (SELECT #row_number:=0) AS t " _
& ") AS sub_query " _
& "WHERE num = '" & counter & "';"
Stack Example: ROW_NUMBER() in MySQL
Adding ConnectionTimeout and default command timeout in connection string fixed this issue for me.
eg.
ConnectionTimeout=300000; default command timeout=300000;

MySQL INSERT causes MySqlException on .ExecuteNonQuery

I am able to connect to the database fine, but when I try to INSERT I get this cryptic error:
Error 0 has occurred: Fatal error encountered during command execution.
I've checked and all of my params have values and they match the column titles exactly except for ID which is auto increment.
Where am I going wrong, please?
Dim iReturn As Boolean
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim strConnection = "server=" & txtServer.Text & ";" _
& "user id=" & txtUsername.Text & ";" _
& "password=" & txtPassword.Text & ";" _
& "database=" & txtDatabase.Text
conn.ConnectionString = strConnection
Try
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO twc_data VALUES(#todaysdate,#fname,#mname,#lname,#address,#city,#state,#zip,#email,#arPhone(0),#arPhone(1),#arPhone(2),#arCategory(0),#arCategory(1),#arJob1(1),#arJob1(2),#arJob1(3),#arJob1(4),#arJob1(5),#arJob2(1),#arJob2(2),#arJob2(3),#arJob2(4),#arJob2(5),#arJob3(1),#arJob3(2),#arJob3(3),#arJob3(4),#arJob3(5),#arCategory(2),#arCategory(3),#arCategory(4),#arCategory(5),#arCategory(6),#arCategory(7),#arCategory(8),#arCategory(9),#arCategory(10),#pdfilename,#strText)"
cmd.Prepare()
With cmd
.Prepare()
.Parameters.AddWithValue("#todaysdate", param(0))
.Parameters.AddWithValue("#fname", param(1))
.Parameters.AddWithValue("#mname", param(2))
.Parameters.AddWithValue("#lname", param(3))
.Parameters.AddWithValue("#address", param(4))
.Parameters.AddWithValue("#city", param(5))
.Parameters.AddWithValue("#state", param(6))
.Parameters.AddWithValue("#zip", param(7))
.Parameters.AddWithValue("#email", param(8))
.Parameters.AddWithValue("#arPhone(0)", param(9))
.Parameters.AddWithValue("#arPhone(1)", param(10))
.Parameters.AddWithValue("#arPhone(2)", param(11))
.Parameters.AddWithValue("#arCategory(0)", param(12))
.Parameters.AddWithValue("#arCategory(1)", param(13))
.Parameters.AddWithValue("#arJob1(1)", param(14))
.Parameters.AddWithValue("#arJob1(2)", param(15))
.Parameters.AddWithValue("#arJob1(3)", param(16))
.Parameters.AddWithValue("#arJob1(4)", param(17))
.Parameters.AddWithValue("#arJob1(5)", param(18))
.Parameters.AddWithValue("#arJob2(1)", param(19))
.Parameters.AddWithValue("#arJob2(2)", param(20))
.Parameters.AddWithValue("#arJob2(3)", param(21))
.Parameters.AddWithValue("#arJob2(4)", param(22))
.Parameters.AddWithValue("#arJob2(5)", param(23))
.Parameters.AddWithValue("#arJob3(1)", param(24))
.Parameters.AddWithValue("#arJob3(2)", param(25))
.Parameters.AddWithValue("#arJob3(3)", param(26))
.Parameters.AddWithValue("#arJob3(4)", param(27))
.Parameters.AddWithValue("#arJob3(5)", param(28))
.Parameters.AddWithValue("#arCategory(2)", param(29))
.Parameters.AddWithValue("#arCategory(3)", param(30))
.Parameters.AddWithValue("#arCategory(4)", param(31))
.Parameters.AddWithValue("#arCategory(5)", param(32))
.Parameters.AddWithValue("#arCategory(6)", param(33))
.Parameters.AddWithValue("#arCategory(7)", param(34))
.Parameters.AddWithValue("#arCategory(8)", param(35))
.Parameters.AddWithValue("#arCategory(9)", param(36))
.Parameters.AddWithValue("#arCategory(10)", param(37))
.Parameters.AddWithValue("#pdfilename", param(38))
.Parameters.AddWithValue("#strText)", param(39))
End With
cmd.ExecuteNonQuery()
iReturn = True
Catch ex As MySqlException
param(40) = "Error " & ex.Number & " has occurred: " & ex.Message
logError()
iReturn = False
Finally
conn.Close()
End Try
Return iReturn
You should specify the column names of the table with out ID.
INSERT INTO twc_data([column names of the table]) VALUES(#todaysdate,.....

VB.net not working with SQL

I have a problem that is eating my brains out.
I have a project with 2 forms : 1 that extracts the data from my database ( name and surname) and another one that checks out if the user input of the user is correct (matching name and surname) . The code for the 1'st form is :
http://pastebin.com/rg5GMuu6
The code for the second is pasted here
I have no idea whatsoever how to repair this error. I've heard something about some sort of an adapter or something......Help
Ty in advance
I am using MySQL (Easy PHP);
Uploading some pics:
The first form is working without any problems, the second one gives me this error
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class Form2
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
'just a message
MsgBox(" You are searching for the users: " & vbCrLf & "Name: " & TextBox1.Text & vbCrLf & "Surname: " & TextBox2.Text)
' connecting to the database
dbCon = New MySqlConnection("Server = localhost; Database = users; Uid = root; Pwd = password")
strQuery = "SELECT users.name, users.surname FROM users" & _
" WHERE users.name = #Username AND users.surname = #UserPassword"
SQLCmd = New MySqlCommand(strQuery, dbCon)
SQLCmd.Parameters.AddWithValue("#Username ", TextBox1.Text)
SQLCmd.Parameters.AddWithValue("#UserPassword", TextBox2.Text)
'Database open
dbCon.Open()
DR = SQLCmd.ExecuteReader
If DR.HasRows = 0 Then
MsgBox("Not a match", MsgBoxStyle.Critical)
Else
MsgBox("You guessed the correct name: " & TextBox1.Text & "and the surname: " & TextBox2.Text)
End If
'Close
DR.Close()
dbCon.Close()
Catch ex As Exception
MsgBox("Failure to communicate " & vbCrLf & vbCrLf & ex.Message)
End Try
End Sub
End Class
Captured all the errors with the debugger
There seems to be odd situations with the .AddWithValue statement. I have found it better to set parameter values with the following two lines of code.
cmd.Parameters.Add(New SqlParameter("#UserName", Data.SqlDbType.NVarChar)).Direction = ParameterDirection.Input
cmd.Parameters("#UserName").Value = textbox1.text'obviously don't need this if it is an Output Param

The connection property has not been set or is null

When I run this function
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim command As MySqlCommand = New MySqlCommand
Dim sqlQuery As String = "INSERT INTO bookings SET Date=" & "'" & strDateToBook & "',RoomID='" & strComputerRoomToBook & "',Length='" & intNewBookingLength & "',Period='" & intNewStartPeriod & "',UserID='" & intid & "'"
Dim reader As MySqlDataReader
SQLConnection.Open()
command.CommandText = sqlQuery
command.Connection = SQLConnection
reader = command.ExecuteReader
SQLConnection.Close()
Catch excep As Exception
MsgBox(excep.ToString)
End Try
Next
in my program I get an error saying "The connection property has not been set or is null"
How can I get rid of this?
It goes to the exception when it gets to SQLconnection.Open()
I created the ServerString and MySQL connection at the top of the module like so:
Dim ServerString As String = "Server=localhost;User Id=root;Password=**********;Database=rooms"
Dim SQLConnection As MySqlConnection = New MySqlConnection
You are opening a connection without its property
It should be,
Dim SQLConnection As New MySqlConnection(ServerString)
SQLConnection.Open
Also, you may want to use the USING function so that your connection is properly closed.
It seems you are just inserting a bunch of values to your database and not retrieving anything so why do you use a DataReader?
Your code should be something like this:
Using SQLConnection = New MySqlConnection(ServerString)
SQLConnection.Open 'You should open a connection only once
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim sqlQuery As String = "INSERT INTO bookings SET " & _
"Date='" & strDateToBook & "'," & _
"RoomID='" & strComputerRoomToBook & "', " & _
"Length='" & intNewBookingLength & "', " & _
"Period='" & intNewStartPeriod & "', " & _
"UserID='" & intid & "'"
Dim command = New MySqlCommand(sqlQuery, SQLConnection)
command.ExecuteNonQuery
Catch excep As Exception
MsgBox(excep.Message)
End Try
Next
End Using
Also, you may want to change how to pass your values into a parameter. This will prevent SQL Injection.