VB.NET MySQL query returns no value - mysql

I am trying to display value in combobox using MySQL in vb.net. Right now the problem that I am facing is that combobox is not displaying values from MySQL. I have the below code:
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "DB Connection Successful"
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label10.Text = READER.GetDouble("Price")
End While
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
However, using the above code Combobox1.Text returns nothing but if I use below code which has a different query it works:
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "DB Connection Successful"
Dim Query As String
Query = "select * from s974_db.processors"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sName = READER.GetString("Name")
ComboBox1.Items.Add(sName)
End While
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
Could someone please check and let me know what could be the issue? Thanks!

so the highlights as i mentioned them in the comments
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' You need only to open aconnection once
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "server=localhost;userid=root;password=root;database=s974_db"
Try
MySqlConn.Open()
Label21.Text = "db connection successful"
'First load both Combobox
Dim query As String
query = "select * from s974_db.processors"
COMMAND = New MySqlCommand(query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim sname = READER.GetString("name")
ComboBox1.Items.Add(sname)
ComboBox2.Items.Add(sname)
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Closing
Try
MySqlConn.Close()
MySqlConn.Dispose()
Catch ex As Exception
End Try
End Sub
ANd now the Comboboxes
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
'Only when there is a item selected , ask for data
If ComboBox1.SelectedIndex > -1 Then
Try
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label11.Text = READER.GetDouble("Price")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End If
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
If ComboBox2.SelectedIndex > -1 Then
Try
Dim Query As String
Query = "select * from s974_db.processors where Name='" & ComboBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MySqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Label10.Text = READER.GetDouble("Price")
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
End Try
End If
End Sub
This is exactly as i described on Form_load you fill both comboboxes
When you now change one of the comboxes one of the label change too.
Sometimes you have to update the Element to see a change
in that case you write at the end of the loop
Label10.Update()

Starting at the top...
Keep your database objects local to the method where they are used. (Not Form level variables) You can make the connection string a class level string variable. This is the only way you can ensure that they are closed and disposed.
Using...End Using blocks will close and dispose your database objects even if there is an error. The constructor of the connection takes the connection string. Connections are precious objects. Don't open the connection until directly before the .Execute method and close it as soon as possible.
It doesn't make much sense that the user could select an item from ComboBox1 before the Form.Load.
In general, we don't want to download anymore data than necessary and we want to hit the database as little as possible. In the Form.Load we bind the combobox to a data table that contains the name and price fields, setting the display and value members. Now, whenever the user picks a name in the combo we can retrieve the price without connecting to the database again.
I noticed that you were using Val in another event. This is an old VB6 method that can give you unexpected results. .Net and vb.net have all sorts of ways to get numbers out of strings that are faster and more reliable. CInt, .TryParse, .Parse, CType, Convert.To etc.
Public Class Form1
Private ConString As String = "server=localhost;userid=root;password=root;database=s974_db"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Fill combobox
Dim dt As New DataTable
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("select Name, Price from processors;", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using 'Closes and disposes both connection and command
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "Price"
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
Label10.Text = ComboBox1.SelectedValue.ToString
ClearLabels()
End Sub
Private Sub ClearLabels()
Label11.Text = ""
Label12.Text = ""
Label13.Text = ""
Label14.Text = ""
Label15.Text = ""
Label16.Text = ""
Label17.Text = ""
Label18.Text = ""
Label19.Text = ""
Label20.Text = ""
End Sub
End Class

Related

Database values in textbox if select Combobox vb.net mysql

i cant figure out my problem there is no error but value in combobox not showing from mysqldatabase
here is my code
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New MySqlConnection
conn.ConnectionString = "server=localhost;user vbid=root;password=admin;database=dnidb"
Dim reader As MySqlDataReader
Try
conn.Open()
Dim query As String
query = "select * from dnidb.hargapro where NamaP = '" & ComboBox1.Text & "'"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
While reader.Read
TextBox8.Text = reader.GetInt32("HargaP")
End While
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
this code was no error, but didnt show anything in the combobox, i try to make this cone on combobox_selectedindexchanges and same thing nothing showing up in the combobox
i just follow the code from here
https://www.youtube.com/watch?v=HfnoGEmRGvc
I don't see any code that tries to retrieve the product names to combobox, and it seems like the above code should be on SelectedIndexChanged event of the combobox.

VB NET + Substring + Mysql + Check Rows

I have a simple form with a button and 2 textbox.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection(ConfigurationManager.ConnectionStrings("db.My.MySettings.dbConnectionString").ToString)
Try
'MysqlConn.Dispose()
'MysqlConn.Close()
MysqlConn.Open()
Dim str As String
str = "SELECT substring_index(substring(path,1,locate(substring_index(path,'\\',-1),path)-2),'\\',-1)as PATH FROM foto where id_product = '" & TextBox2.Text & "'"
Dim dbCommand As New MySqlCommand(str, MysqlConn)
Dim dbReader = dbCommand.ExecuteReader
While dbReader.Read()
If IsDBNull(dbReader(0)) OrElse String.IsNullOrEmpty(dbReader.GetString(0)) Then
TextBox1.Text = "0"
Else
TextBox1.Text = dbReader.Item("PATH")
End If
End While
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
when i put in textbox2 "1" i have my desired value.
But when i put "2", this id_product dont exist, i dont have "0".
It's blank and Textbox1 has my previous value.
What i do wrong ??
If the query doesn't return any record, your code doesn't enter the while loop (dbReader.Read return false) and thus you don't set the textbox to "0" but you should also start to use parameterized queries. It is very important to avoid possible parsing errors and mainly to avoid Sql Injection attacks
So, you could test if your query has produced any record verifying the property HasRows of the DataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using MysqlConn = New MySqlConnection(ConfigurationManager.ConnectionStrings("db.My.MySettings.dbConnectionString").ToString)
Try
MysqlConn.Open()
Dim str As String
str = "SELECT substring_index
(substring(path,1,
locate(substring_index(path,'\\',-1),path)-2),
'\\',-1) as PATH
FROM foto where id_product = #pid"
Dim dbCommand As New MySqlCommand(str, MysqlConn)
dbCommand.Parameters.Add("#pid", MySqlDbType.VarChar).Value = textBox2.Text
Using dbReader = dbCommand.ExecuteReader
if dbReader.HasRows Then
While dbReader.Read()
If IsDBNull(dbReader(0)) OrElse String.IsNullOrEmpty(dbReader.GetString(0)) Then
TextBox1.Text = "0"
Else
TextBox1.Text = dbReader.Item("PATH")
End If
End While
else
TextBox1.Text = "0"
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub

how to display selected value in mysql database in label through vb.net

i have a code but it's not working. i was trying to put a value in label2 but it's not working. please help me.
Private Sub student_no_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles student_no.Click
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server = localhost; port=3307; user id = root; password = 1234; database = sample;"
Dim READER As MySqlDataReader
Try
MySqlConnection.Open()
Dim query As String
query = " select id from sample.student where last_name = '" & txtlastname.Text & "' "
Dim Command As New MySqlCommand(query, MySqlConnection)
READER = Command.ExecuteReader
Label2.Text = query.ToString
MessageBox.Show("Student Number Generated")
MySqlConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MySqlConnection.Dispose()
End Try
End Sub
You are using .ToString on query, which is a string. What you should be doing is operations on the READER object.
Since SELECT will always return a list of results, you have to treat the results as such, like...
While READER.Read()
MessageBox.Show((READER.GetInt32(0)))
End While
.Read() returns the next element in the returned rowset
If READER.Read() Then
Label2.Text = READER.GetString(0)
End If

delete and update command not working.....program in asp.net2010, SQLYOG DATABASE 5.0

in ths program my DISPLAY and ADD button is working but at the time of UPDATE and DELETE record it gives the exception error i.e CHECK THE MANUAL THAT CORRESPONDS TO YOUR MYSQL SERVER FOR THE RIGHT SYNTAX.....
can you please correct my syntax...?
Imports MySql.Data.MySqlClient
Imports System.Data
Partial Class _Default Inherits System.Web.UI.Page
Dim connection As MySqlConnection = New MySqlConnection("data source=localhost;database=dbconnect;user id=root;password=search;")
Dim mydataset As New DataSet()
Dim mydataadpter As MySqlDataAdapter = New MySqlDataAdapter()
Public query As String
' Dim con As MySqlConnection = New MySqlConnection("data source=localhost;database=dbconnect;user id=root;password=search;")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
connection.Open()
End Sub
Protected Sub btn_display_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_display.Click
Dim mysql As MySqlCommand = New MySqlCommand("select * from userinfo", connection)
mydataadpter.SelectCommand = mysql
mydataadpter.Fill(mydataset, "product")
Try
GridView1.DataSource = mydataset
GridView1.DataBind()
GridView1.DataMember = "product"
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_add.Click
query = "INSERT INTO userinfo VALUES("
query = query + txt_userid.Text + ",'" + txt_username.Text + "'," + txt_age.Text + ")"
Dim MySqlCommand = New MySqlCommand(query, connection)
Dim i As Integer = MySqlCommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is saved")
Else
MsgBox("record is not saved")
End If
End Sub
Protected Sub btn_update_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_update.Click
Try
query = "UPDATE USERINFO SET username='" + txt_username.Text + "',"
query = query + "age=" + txt_age.Text
query = query + "WHERE userid=" + txt_userid.Text
Dim mysqlcommand = New MySqlCommand(query, connection)
MsgBox(query)
Dim i As Integer = mysqlcommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is updated")
Else
MsgBox("record is not updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_delete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_delete.Click
Try
query = "DELETE FROM userinfo WHERER userid=" + txt_userid.Text
Dim mysqlcommand As New MySqlCommand(query, connection)
MsgBox(query)
Dim i As Integer = mysqlcommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is deleted")
Else
MsgBox("record is not deleted")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Your query seems to be syntactically correct, however, I would always use a parameterized query instead of a string concatenation. This will avoid Sql Injection and the quoting around the parameter value will be carried out by the framework code.
Try this for the update method
Try
query = "UPDATE USERINFO SET username=#uname, age=#uage WHERE userid = #uid";
Dim mysqlcommand = New MySqlCommand(query, connection)
mysqlcommand.Parameters.AddWithValue("#uname", txt_username.Text))
mysqlcommand.Parameters.AddWithValue("#uage",Convert.ToInt32(txt_age.Text))
mysqlcommand.Parameters.AddWithValue("#uid",Convert.ToInt32(txt_userid.Text))
Dim i As Integer = mysqlcommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is updated")
Else
MsgBox("record is not updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Another important thing to fix in your code is the global connection object. Don't do that. If one of your query fails for whatever reason you leave the connection open and that is a serious problem for the stability of your code.
Try
query = "UPDATE USERINFO SET username=#uname, age=#uage WHERE userid = #uid";
Using con = new MySqlConnection(.......)
Using cmd = new MySqlCommand(query, con)
con.Open()
cmd.Parameters.AddWithValue(......)
End Using
End Using
Catch ex As Exception
....
End Try
The using statement is critical to ensure a correct usage of expensive resources like a connection to the database and ensure a proper close and dispose of these kind of objects

Update SQL statement in vb.net

I am new in VB.NET and as well as SQL. I want to update records in my database. I made a dummy in my database.
Example the values are: ID = 1, name=Cath, age=21
In my interface made in VB.NET, I update the values example : name = txtName.Text and age = txtAge.Text where ID = 1. This is in my main form. In my main form, I have "view" button informing that by clicking that button, new form would pop up and would view the updated values by the user. The program does not have any errors except that when I want to update again the values in my SQL, It record BUT when I click "view" button again, It will show the previous inputted by the user (the first update upon running the interface). What should be the solution?
This is my code:
Mainform:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MessageBox.Show("Successful connection")
Else
'SQLConnection.Close()
MessageBox.Show("Connection is closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveNames(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully Added!")
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Dim date_now As String
date_now = Format(dtpDate.Value, "yyyy-MM-dd")
Dim SQLStatement As String = "UPDATE people SET name='" & txtName.Text & "', date ='" & date_now & "' WHERE 1"
SaveNames(SQLStatement)
End Sub
Form 2: (where the updated data would be viewed)
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
'====retrieve / update values in database=============
Dim SQLStatement As String = "SELECT name, date FROM people"
ViewInfos(SQLStatement)
Else
'SQLConnection.Close()
MessageBox.Show("Connection is closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub ViewInfos(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
'--read the records in database in phpmyadmin gui---
Dim myReader As MySqlDataReader = cmd.ExecuteReader
If myReader.Read Then
lblName.Text = myReader.GetString(0)
lblDate.Text = myReader.GetString(1)
End If
myReader.Close()
MsgBox("Records Successfully Retrieved")
End Sub
Any help would be appreciated. Thanks!
You are leaving your connection string open when you update sql, thus when you try to retrieve the data, your condition closes the connection without reading the data or updating your textboxes.
Take out the .ExecuteNonQuery() from the ViewInfos() method.
Refer to your forms via variables not via the form name:
Dim myForm as New Form2()
myForm.Show()