Click on one button multiple times and mySql - mysql

I'm making sort of generator. On each click on button it need to read me a record from database and show it in textbox1 and textbox2.
For now i know how to read from database but how to on each click show different values
Public Class form1
Dim mysqlconnection As MySqlConnection
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
mysqlconnection = New MySqlConnection()
mysqlconnection.ConnectionString = " Hidden "
Try
mysqlconnection.Open()
Catch myerror As MySqlException
MessageBox.Show("Cannot connect to database: " & myerror.Message)
End Try
Dim myadapter As New MySqlDataAdapter
Dim sqlquary = "SELECT * FROM bazatestna.Users"
Dim command As New MySqlCommand
command.Connection = mysqlconnection
command.CommandText = sqlquary
myadapter.SelectCommand = command
Dim mydata As MySqlDataReader
mydata = command.ExecuteReader()
If mydata.HasRows = 0 Then
MsgBox("Database has no records")
Else
'Ths is the part where i need to show values on click
End If
End Sub
End Class
I would love on load to read all data from mysql database and then whenever i click on button to show one record from database.

This is how I would do it: I declare a variable and place it under Form1 Class:
Public Class Form1
Dim cnt as Integer = 1
Then add 1 increment of cnt inside your button click event:
cnt +=1
Then modify your query string to add limit:
Dim sqlquary = "SELECT * FROM bazatestna.Users Limit " & cnt & ", 1"
To make the program run a little faster, move your connection declarations to the form load event:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
mysqlconnection = New MySqlConnection()
mysqlconnection.ConnectionString = " Hidden "
Try
mysqlconnection.Open()
Catch myerror As MySqlException
MessageBox.Show("Cannot connect to database: " & myerror.Message)
End Try
End Sub

Related

VB.NET MySQL query returns no value

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

MySQL query (sum) not working in VB

I want to add the ages of all the employees in MySQL database column(using sum query) and then want to display its result(the value)on the click of a button in VB in a textbox.I have given a try but its not working.I am not able to figure this out.Please help....Image
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim Mysqlconn As New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=andy1234;database=data"
Try
Mysqlconn.Open()
command.Connection = Mysqlconn
command.CommandText = "select sum(age) from data.etable"
Dim sqlresult As Object
sqlresult = command.ExecuteScalar
Dim str As String
str = sqlresult
TextBox5.Text = str
Mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Mysqlconn.Dispose()
End Try
End Sub
a demo on standard port 3306 for Mysql
Schema
create table etable
( eid int auto_increment primary key,
age int not null
);
insert etable(age) values (1),(2),(3);
VB Code
Imports MySql.Data.MySqlClient
Public Class Form1
Dim conn As New MySqlConnection
Public Sub connect()
' Perform a connection test, and save ConnectionString
' in Module-level variable "conn"
Dim dbname As String = "dbname"
Dim hostname As String = "hostname"
Dim user As String = "dbuser"
Dim password As String = "password"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}", hostname, user, password, dbname)
Try
conn.Open()
MsgBox("Connection Test Successful")
' and ConnectionString set for subsequent queries
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close() ' close connection for now
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
connect()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim iAgeSum As Integer
Try
conn.Open()
Catch ex As Exception
End Try
Dim cmd As New MySqlCommand(String.Format("select sum(age) as ageSum from etable"), conn)
Dim result = cmd.ExecuteScalar()
If result Is Nothing Then
TextBox1.Text = "junk"
Else
iAgeSum = Convert.ToInt32(result.ToString()) ' for the purpose of showing conversion
TextBox1.Text = iAgeSum
End If
conn.Close()
End Sub
End Class
Screenshot

update query not working when i attach the content of text box using data reader on page load

Code works fine when i remove the page load content. this is a form which will allow user to edit the data already present in database. i just want to let a user edit a form which he have already submitted.
This is the code:
Dim con As New SqlConnection("Data Source=ENCODER-PC\SQLEXPRESS;Integrated Security=True")
Dim cmd, com As New SqlCommand
Dim dr As SqlDataReader
Dim n, d, a As Integer
Dim returnValue As Object
Dim str As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
str = "select * from School where RollNo=11"
com = New SqlCommand(str, con)
dr = com.ExecuteReader()
con.Open()
If (dr.Read()) Then
Enroll.Text = dr("RollNo").ToString()
Name.Text = dr("Name").ToString()
Class.Text = dr("Class").ToString()
End If
con.Close()
dr.Close()
End Sub
Protected Sub Next_Click(sender As Object, e As EventArgs) Handles [Next].Click
Try
cmd.CommandText = "Update School SET RollNo='" & Enroll.Text & "', Name='" & Name.Text & "', Class='" & Class.Text & "' where RollNo=11 "
cmd.Connection = con
con.Open()
MsgBox("Connection is Open ! ")
n = cmd.ExecuteNonQuery
If n > 0 Then
MsgBox("data inserted successfully")
Else
MsgBox("data insertion failed")
End If
Catch ex As Exception
MsgBox(ex.ToString())
Finally
con.Close()
End Try
End Sub
You have tagged your question with MySql but in code you use the classes for Sql Server and a connection string specific to Sql Server.
So you should clarify this point. However, in the meantime I wish to give an answer to some errors in your Page_Load event handler:
First you need to check if the call to Page_Load is a postback from other controls and avoid to reload the data from the database in that case. See ASP.NET Page Life Cycle
Second, open the connection before executing the reader
Dim constring = "Data Source=ENCODER-PC\SQLEXPRESS;Integrated Security=True"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim str = "select * from School where RollNo=11"
If Not IsPostBack Then
Using con = new SqlConnection(conString)
Using cmd = new SqlCommand(str, con)
con.Open()
Using dr = com.ExecuteReader()
If (dr.Read()) Then
Enroll.Text = dr("RollNo").ToString()
Name.Text = dr("Name").ToString()
Class.Text = dr("Class").ToString()
End If
End Using
End Using
End Using
End If
End Sub
As you can see there are other improvements: No more global variables for connection, command and reader and Using Statement around the disposable objects.
If this code is really intended to run against a MySql database then you need to use the appropriate classes like MySqlConnection, MySqlCommand, MySqlDataReader etc.. and fix the connectionstring

VB.NET: can't read database records with MySQL Data Reader dr.HasRows

when i click the button 2 with the valid ID No. on the text box it always shows the message box "Invalid ID No." but if i remove the IF statement, it shows database records and it works fine, but i need this IF statement, i think the problem here is the dr.HasRows but i don't know what to put.
Imports MySql.Data.MySqlClient
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;database=db")
Dim DataSet1 As New DataSet
Dim dr As MySqlDataReader
Dim da As New MySqlDataAdapter
Dim cmd As New MySqlCommand
con.ConnectionString = "server = localhost; user id = root;password=root; database = db"
cmd.Connection = con
con.Open()
cmd.CommandText = "select * from voter where idn='" & TextBox1.Text & "'"
dr = cmd.ExecuteReader
con.Close()
da.SelectCommand = cmd
da.Fill(DataSet1, "db")
If dr.HasRows Then
Label2.DataBindings.Add("text", DataSet1, "db.fname")
Label10.DataBindings.Add("text", DataSet1, "db.mi")
Label11.DataBindings.Add("text", DataSet1, "db.lname")
Label12.DataBindings.Add("text", DataSet1, "db.yr")
Label13.DataBindings.Add("text", DataSet1, "db.sec")
Label14.DataBindings.Add("text", DataSet1, "db.vstatus")
Else
MessageBox.Show("Invalid ID No.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Label2.DataBindings.Clear()
Label10.DataBindings.Clear()
Label11.DataBindings.Clear()
Label12.DataBindings.Clear()
Label13.DataBindings.Clear()
Label14.DataBindings.Clear()
End Sub
End Class
You need to use Parameterized query to prevent SQL Injection
Dim commandText as String = "SELECT * FROM Voter WHERE idn=#idn"
Dim command As New MySqlCommand(commandText, connection)
command.Parameters.AddWithValue("#idn", TextBox1.Text)
You don't need to use DataSet and DataAdapter if you are using a DataReader because you could convert your DataReader to a DataTable:
dr = command.ExecuteReader() ' Get Data Reader Rows
dt.Load(dr) 'Convert DataReader into DataTable
Which now could be bind to your Label or TextBox:
Label2.DataBindings.Add("Text", dt, "fname")
You don't need then to use HasRows property to check if DataReader has rows, instead you could check the Row Count of your DataTable:
If (dt.Rows.Count > 0) Then
Label2.DataBindings.Add("Text", dt, "fname")
End If
I am also using the Using statement in dotNet specially for connection so that you don't have to close:
Using connection As New MySqlConnection(connectionString)
'More code here
End Using ' Close the connection automatically
Check Complete Code Below:
Imports MySql.Data.MySqlClient
Public Class Form16
Dim connectionString as String = "server = localhost; user id = root;password=root; database = db"
Dim dt as DataTable
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Using connection As New MySqlConnection(connectionString)
' Use Parameterized query
Dim commandText as String = "SELECT * FROM Voter WHERE idn=#idn"
Dim command As New MySqlCommand(commandText, connection)
Dim dr As MySqlDataReader
' Add idn value using parameterized query
command.Parameters.AddWithValue("#idn", TextBox1.Text)
Try
connection.Open() ' Open Connection
dr = command.ExecuteReader()
dt = New DataTable()
dt.Load(dr)
If (dt.Rows.Count > 0) Then
Label2.DataBindings.Add("Text", dt, "fname")
Label10.DataBindings.Add("Text", dt, "mi")
Label11.DataBindings.Add("Text", dt, "lname")
Label12.DataBindings.Add("Text", dt, "yr")
Label13.DataBindings.Add("Text", dt, "sec")
Label14.DataBindings.Add("Text", dt, "vstatus")
Else
MessageBox.Show("Invalid ID No.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Using
End Sub
End Class
You have done more work than you have to...if you are going to use a datareader, your code should end up looking something like this. (I have not tested this code)
Imports MySql.Data.MySqlClient
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;database=db")
Dim DataSet1 As New DataSet
Dim dr As MySqlDataReader
Dim da As New MySqlDataAdapter
Dim cmd As New MySqlCommand
con.ConnectionString = "server = localhost; user id = root;password=root; database = db"
cmd.Connection = con
con.Open()
cmd.CommandText = "select * from voter where idn='" & TextBox1.Text & "'"
dr = cmd.ExecuteReader
con.Close()
if dr.read then
Label2.text = dr("fname")
Label10.text = dr("mi")
Label11.text = dr("lname")
Label12.text = dr("yr")
Label13.text = dr("sec")
Label14.text = dr("vstatus")
else
MessageBox.show("Invalid ID Number")
endif
End Class

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()