Putting values from MySql query onto form in vb - mysql

I'm trying to extract values from my MySql table and put them onto a form in VB. I want the user to have a list of all the movies he/she is currently renting. I know the MySql statement works so its just a problem with actually getting at the values. Any help would be great! I have the following code:
Private Sub Form9_Load(sender As Object, e As EventArgs) Handles MyBase.Load
NoMovies.Visible = False
Dim query As String
Dim ans As String
Dim ds As New DataSet
Dim da As New MySqlDataAdapter
MysqlConn = New MySqlConnection
Dim Reader As MySqlDataReader
'another query and a two table join'
query = "SELECT movie_name from movie2 Where movie_id=(SELECT movie_id from rental where client_username='" & currentUser & "' AND start_date<='" & DateTime.Now.ToString("yyyy-MM-dd") & "' AND return_date>='" & DateTime.Now.ToString("yyyy-MM-dd") & "')"
MysqlConn.ConnectionString =
"server=mysql.scss.tcd.ie;userid=murpha83;password=gh8ht6789;database=murpha83_db"
MysqlConn.Open()
Command = New MySqlCommand(query, MysqlConn)
da = New MySqlDataAdapter(Command)
da.Fill(ds, "Subject_Detail")
Reader = Command.ExecuteReader
If Reader.HasRows = True Then
'Think I Should extract the values and put them on the form here '
Else
NoMovies.Visible = True
End If
MysqlConn.Close()
Reader.Close()
End Sub
Thanks,
Alan.

Related

reading and comparing data values in MySQL database in vb.net

I'm trying to collect input from the user, check it against my database, and see if it exists in the database. If it does the program is supposed to fetch the last name, first name, and fees of the respective individual and output it.
Code:
Imports Mysql.Data.MySqlClient
Public Class Form1
Dim reader As MySqlDataReader
Dim command As New MySqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myConnectionString As String
myConnectionString = "server=localhost;" _
& "uid=root;" _
& "pwd=Emma#21*GCTU;" _
& "database=dummystudents"
Try
Dim conn As New MySql.Data.MySqlClient.MySqlConnection(myConnectionString)
conn.Open()
Dim sql As String = "SELECT idstudents FROM students WHERE idstudents = #TextBox1.Text "
command = New MySqlCommand(sql, conn)
reader = command.ExecuteReader()
If reader.Read() Then
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
End If
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
Here's your SQL code:
SELECT idstudents FROM students WHERE idstudents = #TextBox1.Text
What's the point of pulling idstudents out when that's the value you're putting in? Worse, though, that's ALL you're pulling out, then you do this:
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
which would require you to pull back at least four columns.
The modification mentioned in the comments may well get your code to execute but it's not the right way to go. It looks like you tried to use a parameter but failed. Do that but do it right, i.e.
Dim sql As String = "SELECT idstudents, otherColumnsHere FROM students WHERE idstudents = #idstudents"
Using connection As New MySqlConnection(myConnectionString),
command As New MySqlCommand(sql, connection)
command.Parameters.Add("#idstudents", MySqlDbType.Int32).Value = CInt(TextBox1.Text)
conn.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
End If
End Using
End Using

VB.net Check next row if a value doesn't meet the requirements on Mysql

I googled a lot and couldn't find anything.
This is my code:
Imports MySql.Data.MySqlClient
Public Class Website_a_fazer
Dim connection As New MySqlConnection("datasource=localhost;port=3306;username=root;password=;database=website_tester")
Dim command As MySqlCommand
Dim WebsiteATestar As Integer = 1
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim adapter2 As New MySqlDataAdapter("SELECT `id_website`, `website`, `id_tipoutilizador`, `dinheiro` FROM websites WHERE id_tipoutilizador='" & Inicio.TipoUtilizador & "' AND id_website ='" & WebsiteATestar & "' AND ativo = 1", connection)
Dim table As New DataTable()
adapter2.Fill(table)
Dim command As New MySqlCommand("SELECT `id_websitefeito`, `id_utilizador`, `id_website`, `website` FROM websites_feitos WHERE id_utilizador='" & Inicio.IdUtilizador & "' AND id_website ='" & WebsiteATestar & "'", connection)
Dim adapter As New MySqlDataAdapter(command)
Dim table1 As New DataTable()
adapter.Fill(table1)
If table1.Rows.Count = 0 Then
Label2.Text = table(0)(1)
Label4.Text = table(0)(3)
Inicio.IdUrl = table(0)(0)
Inicio.CurrentUrl = Label2.Text
Inicio.DinheiroSite = table(0)(3)
Dim dataSet As New DataTable
Dim bindindsrc As New BindingSource
Dim dataadapt As New MySqlDataAdapter
Try
command = New MySqlCommand("SELECT `objetivo` FROM objetivos_website WHERE id_website='" & Inicio.IdUrl & "'", connection)
dataadapt.SelectCommand = command
dataadapt.Fill(dataSet)
bindindsrc.DataSource = dataSet
DataGridView1.DataSource = bindindsrc
dataadapt.Update(dataSet)
Catch ex As ArgumentException
End Try
Else
WebsiteATestar = WebsiteATestar + 1
End If
End Sub
This is my database:
I want to check the database on table "websites" for the first row that "id_utilizador = 4" and "ativo = 1"
If the table "websites_feitos" has already that website, check the next row of "websites", until it finds a row that meets those requirements.
Could you guys help me with this? I am making this project has a 12ยบ year final project :)

Displaying data from different tables in MySql Database into vb.net 2012 Textboxes

am trying to run some lines of code to enable me display some data from different tables from MySql database in vb.net 2012. This is how it works. When i login with my username and password, it should display the name of my store and branch name in the text box provided using my login details. This code is not written in the login form. below is my code
Imports MySql.Data.MySqlClient
Public Class SelectionForm
Dim sqlconn As MySqlConnection
Dim sqlcmd As MySqlCommand
Private Sub SelectionForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
sqlconn = New MySqlConnection
sqlconn.ConnectionString = "server=localhost;userid=root;password=;database=osap"
Dim sqlreader As MySqlDataReader
'Dim sqladapter As MySqlDataAdapter
Try
sqlconn.Open()
Dim Query As String
Query = "SELECT sales_reps.username, stores.name, branches.name FROM sales_reps, stores, branches WHERE sales_reps.id =(SELECT id FROM sales_reps WHERE username='" & LoginForm.UserTextBox.Text & "' AND password='" & LoginForm.PassTextBox.Text & "') AND branches.id = sales_reps.branch_id AND stores.id = branches.store_id"
sqlcmd = New MySqlCommand(Query, sqlconn)
sqlreader = sqlcmd.ExecuteReader()
If sqlreader.HasRows Then
sqlreader.Read()
BranchTextBox.Text = sqlreader.GetString("branches.name")
StoreTextBox.Text = sqlreader.GetString("stores.name")
End If
sqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
sqlconn.Dispose()
End Try
End Sub
End Class
No errors are displayed but doesn't show the data in the text boxes either.

Filling a datagrid on a form in VB with values from a MySql Database

So I am trying to fill a DataGrid called DataGrid which exists on a form with values from a queryon my database. I am having trouble putting the data into this DataGrid. I have the following code so far:
Private Sub Form9_Load(sender As Object, e As EventArgs) Handles MyBase.Load
NoMovies.Visible = False
DataGrid.Visible = False
Dim query As String
Dim ds As New DataSet
Dim da As New MySqlDataAdapter
MysqlConn = New MySqlConnection
Dim Reader As MySqlDataReader
'another query and a two table join'
query = "SELECT movie_id, movie_name from movie2 Where movie_id=(SELECT movie_id from rental where client_username='" & currentUser & "' AND start_date<='" & DateTime.Now.ToString("yyyy-MM-dd") & "' AND return_date>='" & DateTime.Now.ToString("yyyy-MM-dd") & "')"
MysqlConn.ConnectionString ="server=mysql.scss.tcd.ie;userid=murpha83;password=gh8ht6789;database=murpha83_db"
MysqlConn.Open()
Command = New MySqlCommand(query, MysqlConn)
Reader = Command.ExecuteReader
da = New MySqlDataAdapter(query, MysqlConn)
da.Fill(ds)
da.Fill(DataGrid)
If Reader.HasRows = True Then
DataGrid.Visible = True
Else
NoMovies.Visible = True
End If
MysqlConn.Close()
Reader.Close()
End Sub
I know that the MySql statement works so the problem is just with the DataGrid. The problem is where I try to fill DataGrid with the values from da. I alternatively tried
'DataGrid.DataSource = ds.Tables("movie_name")
as movie_name is the column I want but this didn't work either! Any hlep would be great! Thanks!
Replace
da.Fill(DataGrid)
With
DataGrid.DataSource=ds.Tables[0]

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