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