MySQL INSERT causes MySqlException on .ExecuteNonQuery - mysql

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,.....

Related

MySQL connector not working without net connection

I am creating small database program using MySQL and VB.Net. I am using WampServer for MySQL and MySQL 6.9.8 connector. All code is working fine when I am connected to the internet but when I disconnect, it shows me a "database not found" error. My database is stored locally in Wamp phyMyAdmin
Here is my code
Try
If conn.State = ConnectionState.Closed Then
conn.ConnectionString = "DATABASE=" & My.Settings.myDB & ";" _
& "SERVER=" & My.Settings.myServer & ";user id=" & My.Settings.myUsername _
& ";password=" & My.Settings.myPassword & ";port=" & _
My.Settings.myPort & ";charset=utf8;Convert Zero Datetime=True"
conn.Open()
End If
Catch myerror As Exception
MessageBox.Show("Error Connecting to the database", "Error Database Server", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End
End Try
Here is my other code;
Try
mdlCon.conn.Open()
Dim rd As MySqlDataReader
Dim cmd As New MySqlCommand
Dim dt As New DataTable
cmd.CommandText = "select * from studentdeatil Order by sid DESC"
cmd.Connection = mdlCon.conn
rd = cmd.ExecuteReader
dt.Load(rd)
rd.Close()
For Each rowD As DataRow In dt.Rows
Dim dgvRow As String() = New String() {rowD.Item(3), rowD.Item(1), rowD.Item(2), rowD.Item(4), rowD.Item(5), rowD.Item(6), rowD.Item(7), rowD.Item(8), rowD.Item(9), rowD.Item(10), "", "OLD", rowD.Item(0)}
DataGridView1.Rows.Add(dgvRow)
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Error on INSERT statement

I'm getting an error over and over again, can someone please tell me what's wrong with my INSERT statement?
Here is my code:
Dim SQLcon As New OleDbConnection
Dim SQLdr As OleDbDataReader
Try
SQLcon.ConnectionString = "Provider=Microsoft.ACE.OleDb.12.0;" & _
"Data Source= C:\Users\cleanfuel\Desktop\ProgramniOrig\DBhospital.accdb"
Dim SQLcmd As New OleDbCommand("INSERT INTO tblLogin (Username,Password,SecretQuestion,SecretAnswer)" & _
"VALUES(#Username,#Password,#SecretQuestion,#SecretAnswer)", SQLcon)
SQLcmd.Parameters.AddWithValue("#Username", txtUser.Text)
SQLcmd.Parameters.AddWithValue("#Password", txtPass.Text)
SQLcmd.Parameters.AddWithValue("#SecretQuestion", txtSecretQ.Text)
SQLcmd.Parameters.AddWithValue("#SecretAnswer", txtSecretA.Text)
SQLcon.Open()
MsgBox("Patient Added!", MsgBoxStyle.Information)
SQLdr = SQLcmd.ExecuteReader()
Catch ex As Exception
MessageBox.Show("Error Occured, Can't Register!" & ex.Message)
Finally
SQLcon.Close()
End Try
Return ""
try delimiting the column name PASSWORD with []
Dim _query As String = "INSERT INTO tblLogin (Username, " & _
"[Password], SecretQuestion, SecretAnswer) " & _
"VALUES(#Username, #Password, " & _
"#SecretQuestion,#SecretAnswer)"
Dim SQLcmd As New OleDbCommand(_query, SQLcon)
MS ACCESS Reserved Keywords

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.

Parametized MySQL Insert Command Isn't Working

I tried to parametize my code on my own and I think I may have broken it. Now I can get my application to insert records into my database. Can anyone look through this code and tell me what I'm missing?
EDIT: I modified my code to remove the dbCmd.Dispose() and dbConn.Close() methods as suggested. Now VB is throwing the following exception during debug # the dbCmd.ExecuteNonQuery() line:
Column count doesn't match value count at row 1
HERE'S MY CODE:
Private Sub addCard()
Dim ConnectionString As String = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
Using dbConn As New MySqlConnection(ConnectionString)
dbConn.Open()
'PERFORM CARD ENCRYPTION
Call encryptCard()
'PERFORM DATABASE SUBMISSION
Dim dbQuery As String = "INSERT INTO cc_master (ccType, cardholderFirstname, cardholderLastname, cardholderSalutation, ccLocation, " & _
"ccNumber, ccExpireMonth, ccExpireYear, ccZipcode, ccCode, ccAuthorizedUseStart, ccAuthorizedUseEnd, " & _
"dateAdded, addedBy, customer_accountNumber)" & _
"VALUES(#ccType, #cardholderFirstname, #cardholderLastname, #cardholderSalutation, #ccLocation, " & _
"#ccNumber, #ccExpireMonth, #ccExpireYear, #ccZipcode, #ccCode, #ccAuthorizedUseStart, #ccAuthorizedUseEnd " & _
"#dateAdded, #addedBy, #accountNumber)"
Using dbCmd As New MySqlCommand
With dbCmd
.Connection = dbConn
.CommandType = CommandType.Text
.CommandText = dbQuery
.Parameters.AddWithValue("#ccType", ComboBoxCardType.Text)
.Parameters.AddWithValue("#cardholderFirstname", TextBoxFirstName.Text)
.Parameters.AddWithValue("#cardholderLastname", TextBoxLastName.Text)
.Parameters.AddWithValue("#cardholderSalutation", ComboBoxSalutation.Text)
.Parameters.AddWithValue("#ccLocation", TextBoxLocation.Text)
.Parameters.AddWithValue("#ccNumber", encryptedCard)
.Parameters.AddWithValue("#ccExpireMonth", TextBoxExpireMonth.Text)
.Parameters.AddWithValue("#ccExpireYear", TextBoxExpireYear.Text)
.Parameters.AddWithValue("#ccZipcode", TextBoxZipCode.Text)
.Parameters.AddWithValue("#ccCode", TextBoxCVV2.Text)
.Parameters.AddWithValue("#ccAuthorizedUseStart", Format(DateTimePickerStartDate.Value, "yyyy-MM-dd HH:MM:ss"))
.Parameters.AddWithValue("#ccAuthorizedUseEnd", Format(DateTimePickerEndDate.Value, "yyyy-MM-dd HH:MM:ss"))
.Parameters.AddWithValue("#dateAdded", Format(DateTime.Now, "yyyy-MM-dd HH:MM:ss"))
.Parameters.AddWithValue("#addedBy", FormLogin.TextBoxUsername.Text)
.Parameters.AddWithValue("#accountNumber", TextBoxAccount.Text)
End With
Try
Dim affectedRow As Integer
affectedRow = dbCmd.ExecuteNonQuery()
If affectedRow > 0 Then
MsgBox("Credit/Debit Card Information Saved SUCCESSFULLY!", MsgBoxStyle.Information, "RECORD SAVED")
ButtonReset.PerformClick()
Else
MsgBox("Payment Card Was Not Added!", MsgBoxStyle.Critical, "ATTENTION")
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
dbCmd.Dispose()
End Using
End Using
dbConn.Close()
End Sub
MODIFIED CODE - NOW THROWING EXCEPTION:
Private Sub addCard()
Dim ConnectionString As String = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
Using dbConn As New MySqlConnection(ConnectionString)
'PERFORM CARD ENCRYPTION
Call encryptCard()
'PERFORM DATABASE SUBMISSION
Dim dbQuery As String = "INSERT INTO cc_master (ccType, cardholderFirstname, cardholderLastname, cardholderSalutation, ccLocation, " & _
"ccNumber, ccExpireMonth, ccExpireYear, ccZipcode, ccCode, ccAuthorizedUseStart, ccAuthorizedUseEnd, " & _
"dateAdded, addedBy, customer_accountNumber)" & _
"VALUES(#ccType, #cardholderFirstname, #cardholderLastname, #cardholderSalutation, #ccLocation, " & _
"#ccNumber, #ccExpireMonth, #ccExpireYear, #ccZipcode, #ccCode, #ccAuthorizedUseStart, #ccAuthorizedUseEnd " & _
"#dateAdded, #addedBy, #accountNumber)"
Using dbCmd As New MySqlCommand
With dbCmd
.Connection = dbConn
.CommandType = CommandType.Text
.CommandText = dbQuery
.Parameters.AddWithValue("#ccType", ComboBoxCardType.Text)
.Parameters.AddWithValue("#cardholderFirstname", TextBoxFirstName.Text)
.Parameters.AddWithValue("#cardholderLastname", TextBoxLastName.Text)
.Parameters.AddWithValue("#cardholderSalutation", ComboBoxSalutation.Text)
.Parameters.AddWithValue("#ccLocation", TextBoxLocation.Text)
.Parameters.AddWithValue("#ccNumber", encryptedCard)
.Parameters.AddWithValue("#ccExpireMonth", TextBoxExpireMonth.Text)
.Parameters.AddWithValue("#ccExpireYear", TextBoxExpireYear.Text)
.Parameters.AddWithValue("#ccZipcode", TextBoxZipCode.Text)
.Parameters.AddWithValue("#ccCode", TextBoxCVV2.Text)
.Parameters.AddWithValue("#ccAuthorizedUseStart", Format(DateTimePickerStartDate.Value, "yyyy-MM-dd HH:MM:ss"))
.Parameters.AddWithValue("#ccAuthorizedUseEnd", Format(DateTimePickerEndDate.Value, "yyyy-MM-dd HH:MM:ss"))
.Parameters.AddWithValue("#dateAdded", Format(DateTime.Now, "yyyy-MM-dd HH:MM:ss"))
.Parameters.AddWithValue("#addedBy", FormLogin.TextBoxUsername.Text)
.Parameters.AddWithValue("#accountNumber", TextBoxAccount.Text)
End With
Try
dbConn.Open()
dbCmd.ExecuteNonQuery()
Dim affectedRow As Integer
affectedRow = dbCmd.ExecuteNonQuery()
If affectedRow > 0 Then
MsgBox("Credit/Debit Card Information Saved SUCCESSFULLY!", MsgBoxStyle.Information, "RECORD SAVED")
ButtonReset.PerformClick()
Else
MsgBox("Payment Card Was Not Added!", MsgBoxStyle.Critical, "ATTENTION")
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
End Using
End Using
End Sub
I figured out the solution to the problem. I was missing a comma at the end of #ccAuthorizedUseEnd in the query. I added it and viola, the error is gone and the query is working now.
Thanks.

How can I resolve a fatal SQL statement error?

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