MySQL query (sum) not working in VB - mysql

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

Related

How to select from a cell in mysql and add to button.text

i'm a newbie to visual basic 2015 in visual studio community.
what i'm trying to do on load of main form
i have 7 buttons that need the text field changed to correspond with the entries in the Database. these buttons can be change to now categories by the end user down the road.
I'm using MySQL for my database. Any help would be MUCH appreciated as i have searched google and youtube and it's an endless world of OVERLOAD.
My DB Structure is as follows since i cant embed an image:
idbtncat btn_Name btn_caption PanelNo btn_image
1 btn_cat1 Pizza pnl_cat1 pizza.jpg
Public Class frm_MainConsole
Dim conn As New MySqlConnection
Sub dbconn()
Dim DatabaseName As String = "posdb"
Dim server As String = "localhost"
Dim userName As String = "root"
Dim password As String = "8943117"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, userName, password, DatabaseName)
Try
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub frm_MainConsole_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Show()
dbconn()
Dim query As String
Dim command As MySqlCommand
Dim reader As MySqlDataReader
Try
dbconn()
query = "select * from posdb.button_cat where btn_caption"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
While reader.Read
btn_Cat1.Text = reader("btn_caption")
conn.Close()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
Private Sub testDatabaseConnectionToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles testDatabaseConnectionToolStripMenuItem.Click
If mnit_dbConn.Text = "DB NOT Connected" Then
dbconn()
mnit_dbConn.Text = "DB CONNECTED"
Else
mnit_dbConn.Text = "DB NOT Connected"
conn.Close()
End If
End Sub

Click on one button multiple times and 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

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

VB.NET login with a MySQL database

I do have an annoying problem here, I am not able troubleshoot this issue. My problem is that I cannot confirm my login, somewhere's a logical error because my try-catch block is not 'catching' anything, I even used breakpoints between DataBase Opening and DB.Close to see if there's any issue. Here are some screens :
So if I enter the user Gigel and his password 123 (it's encrypted) I get my false execution from my IF , 'Something's wrong out there'
Error..., anyone ?
Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports System.Security.Cryptography
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MySQLConnection As New MySqlConnection("Server = localhost;Database = users; Uid=root; Pwd = password ")
Dim HashedPass As String = ""
'Converts the Password into bytes, computes the hash of those bytes, and then converts them into a Base64 string
Using MD5hash As MD5 = MD5.Create()
System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(TextBox2.Text)))
End Using
'Counter
Dim SqlQuery As String = "SELECT COUNT(*) From users1 WHERE username = #Username AND password = #Password; "
MySQLConnection.Open()
Dim Command As New MySqlCommand(SqlQuery, MySQLConnection)
'Sanitising parameters
Command.Parameters.Add(New MySqlParameter("#Username", TextBox1.Text))
Command.Parameters.Add(New MySqlParameter("#Password", HashedPass))
'checker
If Command.ExecuteScalar() = 1 Then
MsgBox("Thanks for logging in")
Me.Hide()
Else
MsgBox("Something's wrong down there")
End If
MySQLConnection.Close()
End Sub
End Class
Try this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim MySQLConnection As New MySqlConnection("Server = localhost;Database = users; Uid=root; Pwd = password ")
Dim SqlQuery As String = "SELECT COUNT(*) From users1 WHERE username = #Username AND password = MD5(#Password); "
MySQLConnection.Open()
Dim Command As New MySqlCommand(SqlQuery, MySQLConnection)
Command.Parameters.Add(New MySqlParameter("#Username", TextBox1.Text))
Command.Parameters.Add(New MySqlParameter("#Password", TextBox2.Text))
If Command.ExecuteScalar() = 1 Then
MsgBox("Thanks for logging in")
Else
MsgBox("Invalid username or password")
End If
MySQLConnection.Close()
Catch ex as Exception
MsgBox(ex.Message)
End Sub

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