'Like' statement not producing any results - ms-access

I have a products table where I am trying to search for a value a user enters via a textbox to get a products description, basically any product that might contain the word 'Bread' for example,and the results will be displayed in a combobox, yet my select statement yields no results. When i run the exact same query in access it shows the information so I am not sure if my issue in my code is with the syntax of my query,can someone maybe advise what I am doing wrong here please. I'm using MS Access, and vb.net 2010.
Sub search_prod(ByVal cmb As ComboBox, ByVal searchval As String)
searchval = Trim("'*" & searchval & "*'")
con.Open()
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = "Select (Products.Product_Descr) From [Products] WHERE (Product_Descr LIKE " & searchval & ")"
Dim dr As OleDbDataReader = cmd.ExecuteReader
Do While dr.Read
cmb.Items.Add(dr.GetString(0))
Loop
con.Close()
End Sub

Related

How can I use Excel to interact with MySQL and show result of an SQL query in a cell, after I enter SQL table id in another cell?

I am trying to figure out how to use Excel as an interactive front end to MySQL. It will be my first VBA experience with a database.
My scenario is I want to enter an order number into one cell, and upon completing the input, I want an SQL query to be ran, like SELECT field1, field2 FROM table WHERE order_number = ?, and then display the return result of field1 in a cell. I may use field2 in other cells.
I see there is some code here that may be useful, but I don't know where to enter that code, and how to make that code work after I enter an order number into the cell. I have already made an ODBC Driver connection to where I am able to connect to a database using Excel Database functions. I don't yet know how to use VBA do make a database connection or run interactive queries.
Can you help get me to the point where I can enter an order number in one cell, and see field1 show up in another cell, where field1 will be a value from an SQL query, like the above?
Put code on worksheet where you enter the order number. This uses a DSN created using ODBC Data Source Administrator.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ar As Variant
If Target.Address = "$B$2" Then
ar = GetOrder(Target.Value)
Range("B4") = ar(0)
Range("B5") = ar(1)
End If
End Sub
Function GetOrder(OrderNo As Long) As Variant
Const CONN = "DSN=***;UID=***;PWD=***;"
Const SQL = " SELECT Field1,Field2" & _
" FROM table1 " & _
" WHERE OrderNo = ?"
Dim dbConn As ADODB.Connection, dbCmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim param As ADODB.Parameter, n As Long
Set dbConn = New ADODB.Connection
dbConn.Open CONN
Set dbCmd = New ADODB.Command
With dbCmd
.ActiveConnection = dbConn
.CommandType = adCmdText
.CommandText = SQL
Set param = .CreateParameter("P1", adInteger, adParamInput, 0)
.Parameters.Append param
End With
Set rs = dbCmd.Execute(n, OrderNo)
If Not rs.EOF Then
GetOrder = Array(rs(0).Value, rs(1).Value)
Else
GetOrder = Array("#N/A", "#N/A")
MsgBox "Could not find " & OrderNo, vbExclamation, "Error"
End If
dbConn.Close
End Function

How to populate a ComboBox depending on the selected item from another ComboBox in VB

I have tables inside my MySql database:
material
unitofmeasure
I also have 2 comboboxes:
cmbHeader - this combobox populates the tables inside the database.
cmbContent - this combobox SHOULD populate the columns inside the table selected from cmbHeader
I was able to populate the cmbHeader with the tables inside my database using this code:
Dim conn As New MySqlConnection
Dim command As New MySqlCommand
Dim dt As New DataTable
conn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
Try
conn.Open()
dt = conn.GetSchema("TABLES")
cmbHeader.DataSource = dt
cmbHeader.DisplayMember = "table_name"
cmbHeader.ValueMember = "table_name"
command.Dispose()
conn.Close()
Catch ex As Exception
End Try
Now for the cmbContent, I get an error in my code. I use this code:
Private Sub cmbHeader_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbHeader.SelectedIndexChanged, cmbList.SelectedIndexChanged
Dim conn As New MySqlConnection
Dim command As New MySqlCommand
Dim dt As New DataTable
Dim reader As MySqlDataReader
conn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
conn.Open()
Dim query As String
query = "SELECT * FROM '" & cmbHeader.SelectedItem & "'"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
cmbList.Items.Clear()
While reader.Read
Dim header = reader.GetString("Header")
Dim content = reader.GetString("Content")
Dim convert = reader.GetString("Convert")
cmbList.Items.Add(content)
End While
command.Dispose()
reader.Close()
conn.Close()
End Sub
This is the image of the error that I get using the code above.
I tried changing my query to "SELECT * FROM '" & cmbHeader.SelectedItem.ToString & "'" but I get a different error. How can I populate my 2nd ComboBox depending on what I choose on my 1st ComboBox? Please help I'm stuck. Thanks. :)
Replace following line in your code,
query = "SELECT * FROM '" & cmbHeader.SelectedItem & "'"
with this line,
query = "SELECT * FROM " & cmbHeader.SelectedItem.Value & ";"
Hope this will work.
Thank you.
make your query as like this:
query = "SELECT * FROM " & cmbHeader.Text '<-- updation
OR
query = "SELECT * FROM " & cmbHeader.SelectedValue '<-- updation
but it is not a good practice as it lead to sql injection so i suggest you to do it using parametrized(in this case injuction can be avoided as it allows only selected values from the combo box. but in general it is not a good practice that's why am suggesting like this) query as like the following
query = "SELECT * FROM ?"
Dim cmd As New OdbcCommand
With cmd
.CommandType = CommandType.Text
.CommandText = query
.Connection = con
.Parameters.Add(New OdbcParameter(#table,cmbHeader.SelectedItem ))
End With
FOR OTHER PEOPLE WHO HAVE THE SAME PROBLEM
I was able to figure out what's wrong with my code. The value of the combobox I'm getting returns "Data.Row.DataRowView" that's why my query fails. I changed this:
cmbHeader.DataSource = dt
cmbHeader.DisplayMember = "table_name"
cmbHeader.ValueMember = "table_name"
into this:
cmbHeader.ValueMember = "table_name"
cmbHeader.DisplayMember = "table_name"
cmbHeader.DataSource = dt
Then on my SelectedIndexChanged event, I used this:
Dim value As String = ""
value = Convert.ToString(cmbHeader.Text)
conn.Open()
Dim query As String
query = "SELECT * FROM " & value
command = New MySqlCommand(query, conn)
'With command
' .Parameters.AddWithValue("header", value)
'End With
reader = command.ExecuteReader
cmbList.Items.Clear()
While reader.Read
Dim content = reader.GetString("Content")
cmbList.Items.Add(content)
End While
command.Dispose()
reader.Close()
conn.Close()
Hope this helps. Thanks for the help everyone. :)

MySQL Data NOT Deleting from table VB.NET

Why won't this delete the data in my MySQL database!?
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Try
dbCon = New MySqlConnection("Server=Localhost;Database=myusers;Uid=root;Pwd=Mypassword")
strQuery = "DELETE settings FROM settings WHERE user=" & Me.loginuser.Text
'* FROM settings WHERE user = "Testuser"'
SQLCmd = New MySqlCommand(strQuery, dbCon)
' OPEN THE DB AND KICKOFF THE QUERY
dbCon.Open()
DR = SQLCmd.ExecuteReader
While DR.Read
req1.Text = "" And exlink.Text = ""
End While
' DONE! Close DB
DR.Close()
dbCon.Close()
Catch ex As Exception
TextBox8.Text = ("Fail" & vbCrLf & vbCrLf & ex.Message)
End Try
Here is a picture of my database:
Alternatively I could somehow make it replace what is already in the database, in which case please help me with that.
Try
strQuery = "DELETE FROM settings " _
& " WHERE user = '" & Me.loginuser.Text & "'"
but as was stated earlier, you should be using parameterized queries. If you had a user named O'Brien then your query (as composed above) would fail because of the embedded single quote. When you use DELETE, you are deleting entire records and you already specify the table name in the FROM clause.
I will try to change your code in this way
Using con = New MySqlConnection("Server=.....")
con.Open()
Dim sqlText = "DELETE * FROM settings WHERE user = #ulogin"
Using cmd = new MySqlCommand(sqlText, con)
cmd.Parameters.AddWithValue("#ulogin", Me.loginuser.Text)
cmd.ExecuteNonQuery()
End Using
End Using
First and foremost, do not use string concatenation to create command texts to pass to the database engine. In that way you risk Sql Injections, also, if the user name contains a single quote (i.e. O'Hara) your code will fail with a syntax error (Same problems arise for date formatting, parsing numeric decimals and other globalization issues). Instead a parametrized query like the one in code above will avoid all of these problems.
In a parametrized query, the text of the query doesn't contains the actual value for the search condition or the update or insert data. Instead it contains placeholders ( in our case it is called #ulogin). The correct value to insert at the placeholders position is specified using one or more MySqlParameter added to the Parameters collection of the MySqlCommand. In this case I have used the AddWithValue method that derives the correct datatype directly from the datatype of the value. Because Me.loginuser.Text is a string value then the parameter will be treated as a string value replacing incorrect single quotes and removing extraneus characters usually used to Mount Sql Injections Attacks. The engine will do the rest inserting the correct value at the placeholder at execution time
EDIT: Seeing your comment about the MySql connector used, I will try to update my answer to show a semi-equivalent version for NET 1.
Try
Dim con As MySqlConnection = New MySqlConnection("Server=.....")
con.Open()
Dim sqlText as String = "DELETE * FROM settings WHERE user = #ulogin"
Dim cmd As MySqlCommand = new MySqlCommand(sqlText, con)
Dim par As MySqlParameter = New MySqlParameter("#ulogin", MySqlDbType.VarChar)
par.Value = Me.loginuser.Text
cmd.Parameters.Add(par)
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
I am not sure if the connector 1.0.10 supports the parameter name with the # prefix or just the : prefix
i dont think you can use double quotes in mysql, i think its single quotes only. try
Query = "DELETE * FROM settings WHERE user = '" & Me.loginuser.Text & "'"

ComboBox Isn't Being Populated with MySQL Query Result - How do I resolve it?

I trust you're all well. I would like to know what I'm doing wrong and how to fix it. My intent with the code below is the query my MySQL database and display one column of the table inside a ComboBox. Then, when that value in the ComboBox is selected, I want all the records associated to be populated into other controls on my form (I'll create a separate question for this part).
Right now, the query is working but the ComboBox isn't being populated. What am I doing wrong? Please help, thanks.
HERE'S MY CODE:
Private Sub RetrieveMySQLdata()
Try
Dim dbConn As New MySqlConnection
Dim dbQuery As String = ""
Dim dbCmd As New MySqlCommand
Dim dbAdapter As New MySqlDataAdapter
Dim dbTable As New DataTable
If dbConn.State = ConnectionState.Closed Then
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 = "ccNumber"
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
Where are you trying to populate the ComboBox? The only interaction I see is here:
For i = 0 To dbTable.Rows.Count - 1
ComboBoxCard.ValueMember = "ccNumber"
Next
Which I'm guessing isn't doing what you think it's doing. For one thing, you're setting ValueMember to the same value multiple times in a loop. Nothing in the statement changes with each iteration of the loop, so why loop it?
More specifically, ValueMember isn't actually any kind of displayed value. It's used to indicate which field in the bound data should contain the value. This is used when you provide a DataSource for the control, which you're missing.
I'll assume the DataSource should be dbTable, so you're probably looking to do something like this:
ComboBoxCard.DataSource = dbTable
ComboBoxCard.ValueMember = "ccNumber"
ComboBoxCard.DisplayMember = "Some Other Field in the database"
I don't remember if you need to explicitly call .DataBind() on the control after these statements, but the example I linked to doesn't do it so I'll leave it out.
Essentially what you're trying to do in your code is loop through the results and add them to the ComboBox. You don't need to do this. The ComboBox is capable of doing this internally if you just point its DataSource to the set of data being used and tell it which fields it needs to use on that set. This is called data binding.
It looks like you aren't setting the DataSource for the ComboBox object. Instead of this code:
Dim i As Integer
For i = 0 To dbTable.Rows.Count - 1
ComboBoxCard.ValueMember = "ccNumber"
Next
Use something like this code:
ComboBoxCard.DataSource = dbTable
ComboBoxCard.ValueMember = "ccNumber"
ComboBoxCard.DisplayMember = "(some other column if you want)"

Standard SQL SELECT * FROM TABLE return syntax error

I keep getting an error saying "there is an error in your sql syntax." when i use this sql statement:
SELECT * FROM gsm_oceanwide_integration
EDIT:
To put this in context heres the code im using this query statement in (VB.net):
Dim con As MySqlConnection = New MySqlConnection("Data Source=" & frmLogin.txtserver.Text & ";Database=stratocast;User ID=" & frmLogin.txtusername.Text & ";Password=" & frmLogin.txtpassword.Text & ";")
Dim sqladmin As MySqlCommand = New MySqlCommand("SELECT * FROM employee", con)
Dim sqlprojects As MySqlCommand = New MySqlCommand("SELECT * FROM projects", con)
Dim sqlpage As MySqlCommand = New MySqlCommand("SELECT * FROM '" & frmMain.ListBox1.SelectedItem & "';", con)
Dim ds5 As DataSet = New DataSet()
Dim DataAdapter5 As MySqlDataAdapter = New MySqlDataAdapter()
Dim Comb As MySqlCommandBuilder
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' retrieving the Project Page.
Try
con.Open()
DataAdapter5.SelectCommand = sqlpage
DataAdapter5.Fill(ds5, "stratocast")
DataGridView3.DataSource = ds5
DataGridView3.DataMember = "stratocast"
con.Close()
Catch myerror As MySqlException
MessageBox.Show("Error Retrieving Project Page: " & myerror.Message)
End Try
End Sub
on my frmMain form i have a listbox with a list of projects (one of them being gsm_oceanwide_integration) and i want to make it so that when i click on that selection it will display another form with a datagridview. this datagridview needs to be filled with data from the table i called gsm_oceanwide_integration. (like the listbox selection)
so my current query statement (including vb.net tags) is:
Dim sqlpage As MySqlCommand = New MySqlCommand("SELECT * FROM '" & frmMain.ListBox1.SelectedItem & "';", con)
It was working earlier today, but i must have changed something in it and forgot...
since then the best i can do is get rid of all the errors but the datagridview still won't display anything on my database. Yes, i've checked all the spelling.
UPDATE 2:
I changed my sqlpage command statement from:
Dim sqlpage As MySqlCommand = New MySqlCommand("SELECT * FROM '" & frmMain.ListBox1.SelectedItem & "';", con)
To:
Dim sqlpage As MySqlCommand = New MySqlCommand("SELECT * FROM [" & Me.ListBox1.SelectedItem.Value & "]", con)
and i got a new error on another form all together but it's linked to the listbox1; the code for which is below:
Private Sub ListBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedValueChanged
Form1.indprojectname.Text = ListBox1.SelectedItem
Form1.Show()
End Sub
The error is shown in this screenshot (i thought a screen shot might be the best method for displaying the error details):
the error is: (in case you couldn't read the screenshot)
An error occurred creating the form. See Exception.InnerException for details. The error is: Object variable or With block variable not set.
Also, thanks for the quick replies, sorry i couldn't update my post sooner...
Thanks!
How about the single quote before your double quote around the table name coming in from your listbox? That should not be there. You have:
Dim sqlpage As MySqlCommand = New MySqlCommand("SELECT * FROM '" & frmMain.ListBox1.SelectedItem & "';", con)
It should be:
Dim sqlpage As MySqlCommand = New MySqlCommand("SELECT * FROM " & frmMain.ListBox1.SelectedItem & ";", con)
Steer clear of any adding special characters in your table names or field names. Stick to a convention such as...
myFieldName - known as camel casing or...
my_field_name - just use underscores
As for the sql statement I can't see anything immediately wrong with it. Is the table name correct?
Regarding your query about spaces in table names:
Short Answer - yes but no
However, I would take a look at the MySQL documentation on Schema Object Names
Also as mentioned in the comments, spaces are allowed as a table indentifer using quoted indentifiers but I would not encourage the use of them, mainly for readability reasons.
As for your query, would require more information, such as your list of tables.