I’m using the following code in an attempt to retrieve data from two tables and populate a ComboBox with that information. Then when the user selects a value from the ComboBox, I want to populate all the controls on the form with the data retrieved from the DB that matches the value of the ComboBox (still haven’t figured out how to do this one yet).
NOTE: The 1090 shown in the error is the account number I’m receiving from an InputBox control and then setting the TextboxAccount.Text value to it. So I’m not sure if this is where my problem is.
Here’s the VB exception being thrown:
“You have an error in your SQL syntax; check the manual that
corresponds with your MySQL version for the right syntax to use near
‘customer.accountNumber = ‘1090″ at line 1”
Here’s my code:
Private Sub RetrieveMySQLdata()
Try
'FOR MySQL DATABASE USE
Dim dbConn As New MySqlConnection
Dim dbQuery As String = ""
Dim dbCmd As New MySqlCommand
'Dim dbData As MySqlDataReader
Dim dbAdapter As New MySqlDataAdapter
Dim dbTable As New DataTable
If dbConn.State = ConnectionState.Closed Then
'dbConn = New MySqlConnection
dbConn.ConnectionString = 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)
dbConn.Open()
End If
dbQuery = "SELECT *" & _
"FROM cc_master INNER JOIN customer ON customer.accountNumber = cc_master.customer_accountNumber" & _
"WHERE customer.accountNumber = '" & TextBoxAccount.Text & "'"
With dbCmd
.CommandText = dbQuery
.Connection = dbConn
End With
With dbAdapter
.SelectCommand = dbCmd
.Fill(dbtable)
End With
Dim i As Integer
For i = 0 To dbTable.Rows.Count - 1
ComboBoxCard.ValueMember = "cc_Number"
Next
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 Sub
In this statement:
There’s no space between some of the clauses, such as
cc_master.customer_accountNumberandWHERE. The resulting string would read like:As a general hint with MySQL syntax error messages, when you see a message like this:
You should look just before the part that it’s “near” to find the syntax error. The query parser reads from beginning to end and throws an error when it finds something it can’t interpret. And usually the first thing it can’t interpret is the first thing it sees after the typo/error.
Please note also that using string concatenation is a very bad idea for constructing SQL queries. It leaves you wide open to SQL injection attacks. If you’re using plain old ADO.NET, at the very least you should be using parameterized queries. As a step further, you may want to look into something like LINQ to SQL or Entity Framework which abstracts the database access behind auto-generated code which parameterizes for you behind the scenes.