Parametized MySQL Insert Command Isn't Working - mysql

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.

Related

SQL parameterized? I'm lost

I have no idea how to use parameterized and would like someone to point me into the right direction.
Here's what I'm currently using.
Public Class main
Dim dbCon As New MySqlConnection("Server=localhost;Database=payid;Uid=root")
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Private Sub Use()
Try
strQuery = "UPDATE payid " & _
"SET used='" & amen.Text & "' " & _
"WHERE payid='" & TextBox1.Text & "'"
SQLCmd = New MySqlCommand(strQuery, dbCon)
dbCon.Open()
SQLCmd.ExecuteNonQuery()
dbCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
If someone could change that for me I'd be able to do the rest of my code.
strQuery = "UPDATE payid SET used=#used WHERE payid=#payid "
SQLCmd = New MySqlCommand(strQuery, dbCon)
SQLCmd.Parameters.AddWithValue("#used", amen.Text)
SQLCmd.Parameters.AddWithValue("#payid", TextBox1.Text )

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 with SQL Connection

I get an error when I try to connect to my database.
What I want to do is to check if I have on the same row from my DataBase a name and a surname
ex. Id_ 1 Michael Dawn
I have 2 textboxes and If they include:
Textbox1 - Michael
Textbox2 - Dawn
Then it's a positive match
I get an error :
Need some help with this one guys, thanks
Here is my code
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
'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" & _
"WHERE users.name = '" + TextBox1.Text + "'AND password = '" + TextBox2.Text + "'"
SQLCmd = New MySqlCommand(strQuery, dbCon)
'Database open
Try
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

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.