Mysql ODBC Select command with parameter - not working - mysql

please, can anybody explain why this code is not working?
Connection to mysql is made via mysql odbc driver (latest).
Parameter in Select command is not recognized.
I also tried to replace #param1 in Select command:
Select product_id from product where model = ?
code still not working.
Sub Main()
Dim DBCONT As New Odbc.OdbcConnection
Dim strConn As String = "DSN=MyDSN"
DBCONT.ConnectionString = strConn
DBCONT.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model = #param"
.Connection = DBCONT
End With
Dim param1 As Odbc.OdbcParameter
param1 = cmd.CreateParameter()
With param1
.ParameterName = "#param"
.OdbcType = Odbc.OdbcType.VarChar
.Size = 30
.Value = "TESTVALUE"
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
Console.WriteLine(cmd.CommandText.ToString)
'this line displays "Select product_id from products where model = #param"
'instead of "Select product_id from products where model = "TESTVALUE"..
'WHY??
While reader.Read
Console.WriteLine(reader(0))
Console.WriteLine()
End While
Console.ReadLine()
DBCONT.Close()
reader = Nothing
cmd = Nothing
End Sub

Where it says:
".CommandText = "SELECT product_id FROM products WHERE model = #param"
Change it to:
".CommandText = "SELECT product_id FROM products WHERE model = '#param'"
(I've put ' ' around the #param, keep in mind this is different to the " " that is surrounding this)

I'm not 100% sure but I'll post this as an answer anyway because I think it's correct:
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model = :param"
.Connection = DBCONT
End With
Dim param1 As Odbc.OdbcParameter
param1 = cmd.CreateParameter()
With param1
.ParameterName = "param"
.OdbcType = Odbc.OdbcType.VarChar
.Size = 30
.Value = "TESTVALUE"
End With

Thanks for your help. This code is already working:
Sub Main()
Dim DBCONT As New Odbc.OdbcConnection
Dim strConn As String = "DSN=MyDSN"
DBCONT.ConnectionString = strConn
DBCONT.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model LIKE ?"
//it seems it is important to add paramater right after commandtext
.Parameters.Add("#param", OdbcType.VarChar).Value = "%" + "TESTVALUE" + "%"
.Connection = DBCONT
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
Console.WriteLine(cmd.CommandText.ToString)
//it should display SELECT product_id FROM products WHERE model LIKE ?
While reader.Read
Console.WriteLine(reader(0))
Console.WriteLine()
End While
Console.ReadLine()
DBCONT.Close()
reader = Nothing
cmd = Nothing
End Sub

Related

Visual Basic and Mysql in phpMyadmin [duplicate]

I'm working on my project which displays a list of employee. here, the information and picture of the employee will be shown. my project can now show the list of employees in the listbox and when I double click on an employee, his/her profile will be shown on a textbox. my problem is that i can't make their pictures to show in the picturebox. I already stored their picture on a table in my database along with their id, name, and profile. It only shows the picture of the first employee on the table. can anybody help me?
here's what I already done:
I populated the listbox:
Call Connect()
With Me
STRSQL = "Select employee_name from Employees"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
reader.Close()
adptr.SelectCommand = myCmd
adptr.Fill(dt)
lstEmployee.DisplayMember = "employee_name"
lstEmployee.ValueMember = "employee_id"
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
lstEmployee.Items.Add(dt.Rows(i)("employee_name"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
here's how I show the info on textbox
Dim FileSize As UInt32
Dim mStream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mStream.GetBuffer()
FileSize = mStream.Length
Dim cmd As New MySqlCommandBuilder
Call Connect()
With Me
STRSQL = "select employee_name, profile from Employees where employee_id = " & lstEmployee.SelectedIndex
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
txtName.Text = reader("employee_name")
txtProfile.Text = reader("profile")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
adptr.SelectCommand = myCmd
dt = New DataTable
adptr = New MySqlDataAdapter("select picture from Employees", myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
You miss the where clause is must be like to search a one employee to view there image.
adptr = _
New MySqlDataAdapter("select picture from Employees " + _
"where employee_id = " & lstEmployee.SelectedIndex, myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
P.S.: You must study the LINQ (Language-Integrated Query) for better approach.

How can I solve this cross thread error?

Cross-thread operation not valid: Control textbox accessed from a thread other than the thread it was created on. vb.net
Sub autocompletepayee()
Dim cmd2 As New Odbc.OdbcCommand
Dim dr As Odbc.OdbcDataReader
Dim myquery As String
myquery = "select payee from tbrequest"
cmd2.CommandText = myquery
cmd2.Connection = con
dr = cmd2.ExecuteReader
While dr.Read
txtPayee.AutoCompleteCustomSource.Add(dr.GetString(0)) 'this is the line where the error prompt
End While
dr.Close()
This should work, though it might be shorter if more were known about where the code was located
Dim cmd2 As New Odbc.OdbcCommand
Dim dr As Odbc.OdbcDataReader
Dim myquery As String
myquery = "select payee from tbrequest"
cmd2.CommandText = myquery
cmd2.Connection = con
dr = cmd2.ExecuteReader
While dr.Read
If txtPayee.InvokeRequired Then
txtPayee.Invoke(Sub()
txtPayee.AutoCompleteCustomSource.Add(dr.GetString(0)) 'this is the line where the error prompt
End Sub)
Else
txtPayee.AutoCompleteCustomSource.Add(dr.GetString(0)) 'this is the line where the error prompt
End If
End While
dr.Close()

Save Datagridview if it is Checked by CheckboxColumn

Hello Everyone Good Afternoon,
I have an Object in a form and they are Datagridview1 and a Save Button the Datagridview1 will populate data from my Database on Form_Load and the Data will show with a Corresponding Checkbox. Like the Image below
and If you here is the code for that
Private Sub loadtech()
Dim con1 As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
Dim sql1 As MySqlCommand = New MySqlCommand("select TechName from technicians order by Category ASC", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Technician / Electrician"
End With
DataGridView1.Columns.Item(0).Width = 150
DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Me.DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True
Me.DataGridView1.Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft
Dim checkBoxColumn As New DataGridViewCheckBoxColumn()
checkBoxColumn.HeaderText = "Tag"
checkBoxColumn.Width = 30
checkBoxColumn.Name = "checkBoxColumn"
DataGridView1.Columns.Insert(0, checkBoxColumn)
End Sub
and my Question is how can I save the Checked Row in Database? Lets say I checked all of it so the Rows will be saved in Database. (Regardless of How many I Checked)
Here is my code but its not working. :(
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As MySqlConnection = New MySqlConnection("datasource=localhost;database=operations;userid=root;password=admin1950;Convert Zero Datetime=True")
conn.Open()
Dim comm As MySqlCommand = New MySqlCommand()
comm.Connection = conn
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count
name = Me.DataGridView1.Rows(0).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
Next
conn.Close()
End Sub
TYSM For future help
Yes, your loop is slightly incorrect. Try using this loop and see if that fixes your issue. The issue, you didn't use the i variable. It should be placed in Row(i) and you were looping from 0 to Count when it should be 0 to Count - 1
Dim name As String
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1 Step 1
If Me.DataGridView1.Rows(i).Cells(0).Value = True Then
name = Me.DataGridView1.Rows(i).Cells(1).Value
comm.CommandText = "insert into assignments(ElecAssigned) values('" & name & "')"
comm.ExecuteNonQuery()
End If
Next

How to convert an SQLCOMMAND to INT

I have the following code where table name is student and column name is sem_of_study from the type of INT
Dim userquery As String = "select sem_of_study from student where username='" + Session("user") + "'"
Dim usercom As New SqlCommand(userquery, conn)
Dim a = usercom.ExecuteReader
I was wondering if I could convert the SQL Command into integer so I can use it in IF statements!!
so that variable a would
if a=1 then
else if a=2 then
Besides the fact you should use parameterized queries (search SO -- plenty of examples), you need to do something like this reading in the DataReader rows:
Dim a as Integer
Dim myReader As SqlDataReader = usercom.ExecuteReader()
If myReader.HasRows Then
myReader.Read()
a = myReader.GetInt32(0)
End If
And for the parameters:
Dim userquery As String = "select sem_of_study from student where username=#username"
Dim usercom as SqlCommand = new SqlCommand()
usercom.Connection = conn
usercom.CommandType = CommandType.Text
usercom.CommendText = userquery
usercom.Parameters.AddWithValue("username", Session("user"))

vb.net save in phpmyadmin null values return

I am new in vb.net, sql and even record data in phpmyadmin. When I add the records using my interface, I checked my phpmyadmin and it was indicating to have an entry in the table meaning my vb.net and phpmyadmin is connected but the values returned NULL. How can I make it not NULL? instead ,records the desired data?
This is my code:
Dim ServerString As String = "Server=localhost; database=patientinfo;user id=root;password="
Dim SQLConnection As New MySqlConnection()
Public Sub SaveInfos(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
'MsgBox("Successfully Added!")
MsgBox("Successfully Saved")
Me.Visible = False
Mainform.Show()
SQLConnection.Dispose()
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Try
'===========================Add New Patient========================================
bednumber = txtbednum.Text
patient_name = txtName.Text
patient_age = Convert.ToInt32(txtAge.Text)
date_of_confinement = Date.Parse(dtpDate.Value)
type_of_sickness = txtSickness.Text
type_of_IV_fluid = txtFluid.Text
number_of_bottles = Convert.ToInt32(txtBottle.Text)
drop_rate = Convert.ToInt32(txtDrop.Text)
'To check if all values have been filled up
If patient_name = "" Or patient_age = "" Or date_of_confinement = "" _
Or type_of_sickness = "" Or type_of_IV_fluid = "" Or number_of_bottles = "" Or drop_rate = "" _
Then
MsgBox("Please Complete All the Required Fields")
Else
Dim SQLStatement As String = "INSERT INTO patient(bednumber, name, age, date_of_confinement,type_of_sickness, type_of_IV_fluid, number_of_bottles, drop_rate) VALUES(#bednumber, #name, #age, #date_of_confinement, #type_of_sickness, #type_of_IV_fluid, #number_of_bottles, #drop_rate)"
SaveInfos(SQLStatement)
This what my table looks like in phpmyadmin:
http://i1182.photobucket.com/albums/x454/catherinefbalauro/Untitled.png
Any help would be appreciated. Thanks! :)
Do something like this:
' Assuming that your SQLStatement is as follow
' INSERT INTO MyTableName
' VALUES ( #bednumber, #name, #age,
' #date_of_confinement,#type_of_sickness,
' #type_of_IV_fluid, #number_Of_Bottles,
' #drop_rate
' )
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.Parameters.AddWithValue("#bednumber", txtbednum.Text)
.Parameters.AddWithValue("#name", txtName.Text)
.Parameters.AddWithValue("#age", txtAge.Text)
' dothe same until
' you have added allthe parameter
' with values
SQLConnection.Open()
.ExecuteNonQuery()
End With