Vb.net Mysql Multiple queries in one data - mysql

I'm trying to make a chat in Vb.net using MySQL and I want to load the chat into a list-box where would be the (username) ''par'' and the (message).
But it keeps showing me errors and i don't understand how to solve it.
Here's my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim stringConn As String
Dim stringCmd As String
Dim myConn As MySqlConnection
Dim myCmd As MySqlCommand
stringCmd = "SELECT par, message FROM chat"
stringConn = "server=localhost; user id=studio; password=mypw; database=studio;"
myConn = New MySqlConnection(stringConn)
myCmd = New MySqlCommand(stringCmd, myConn)
myConn.Open()
Dim myReader As MySqlDataReader
myReader = myCmd.ExecuteReader()
'Reset your List box here.
ListBox1.Items.Clear()
While myReader.Read()
--------------Here is my problem ---------------
ListBox1.Items.Add(myReader.GetString(1//username//) & " " & myReader.GetString(2//message//))
----end-- of the---problem---
End While
myReader.Close()
myConn.Close()
End Sub

You could try this:
If myReader.HasRows = True Then
Do While myReader.Read()
ListBox1.Items.Add(myReader(0) & " " & myReader(1))
Loop
End If
Best Regards

Related

How to show data from MySQL in TextBoxes

I need to show a set of data from MySQL like the function of DataGridView or ListView, but using multiple TextBox controls. The result of my work is that all data from a column is together on one TextBox. I don't know how to make a loop.
Code:
Imports System.Data
Imports MySql.Data.MySqlClient
Public Class Form1
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Dim query As String = "SELECT id,timein,timeout FROM emp"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using myCommand As New MySqlCommand("SELECT * FROM emp ORDER BY id ASC", con)
Try
con.Open()
Using myData = myCommand.ExecuteReader()
If myData.HasRows Then
While myData.Read()
Dim idline = String.Format("{0}", myData.GetString(myData.GetOrdinal("id")), Environment.NewLine)
Dim inline = String.Format("{0}", myData.GetString(myData.GetOrdinal("timein")), Environment.NewLine)
Dim outline = String.Format("{0}", myData.GetString(myData.GetOrdinal("timeout")), Environment.NewLine)
idbox1.Text &= idline
idbox2.Text &= idline
idbox3.Text &= idline
timein1.Text &= inline
timein2.Text &= inline
timein3.Text &= inline
timeout1.Text &= inline
timeout2.Text &= inline
timeout3.Text &= inline
End While
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Using
con.Close()
End Sub
End Class
This works fine with me. I got what I need to do. Thank you for the ideas.
"Imports System.Data
Imports MySql.Data.MySqlClient
Public Class Form2
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As MySqlConnection = New MySqlConnection("data source=localhost; user id=root; database=abc; password=")
Dim query As String = "SELECT id,timein,timeout FROM emp"
con.Open()
Dim dt As New DataTable
Dim da As New MySqlDataAdapter("SELECT * FROM emp ORDER BY id ASC", con)
da.Fill(dt)
idbox1.Text = dt.Rows(0)("id").ToString()
idbox2.Text = dt.Rows(1)("id").ToString()
idbox3.Text = dt.Rows(2)("id").ToString()
timein1.Text = dt.Rows(0)("timein").ToString()
timein2.Text = dt.Rows(1)("timein").ToString()
timein3.Text = dt.Rows(2)("timein").ToString()
timeout1.Text = dt.Rows(0)("timeout").ToString()
timeout2.Text = dt.Rows(1)("timeout").ToString()
timeout3.Text = dt.Rows(2)("timeout").ToString()
con.Close()
End Sub
End Class
"
Have you tried using a DataTable? I built a form that pulls values on load from into a DataTable and in that table you can specify the columns that appear and in what order. I used the built in functions in MS VS17 RC to link the tables. Might help you out with your issue.
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sqlConn As New SqlConnection("Connection String Info")
Dim cmd As New SqlCommand
Dim dr As New SqlDataAdapter("-Query String-", sqlConn)
Dim dt As New DataTable
Try
If sqlConn.State = ConnectionState.Closed Then
sqlConn.Open()
dr.Fill(dt)
Menu.DisplayMember = "prod_name" --add your columns here
Menu.DataSource = dt
sqlConn.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Order.Clear()
For Each Item As Object In Menu.SelectedItems
Order.AppendText(Item.ToString = Environment.NewLine)
Next
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

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

button not working when i insert new data

when I input data are not yet available. button does not work
but when I enter existing data in the database, the button work for find existing records in the database and msgbox.appear
this my coding. (i am using Microsoft Visual Basic 2008 express edition database mysql)
Imports MySql.Data.MySqlClient
Public Class Form2
Public conn As MySqlConnection
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Application.DoEvents()
Button1.Focus()
conn = New MySqlConnection
'conn.ConnectionString = "server=localhost;database=ilmu;userid=root;password= ''"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Error1: " & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn = New MySqlConnection("server=localhost;database=ilmu;userid=root;password= ''")
Try
conn.Open()
Dim sqlquery As String = "SELECT * FROM visitor WHERE nama = '" & TextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If data(2).ToString = TextBox2.Text Then
command = New MySqlCommand
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES ('" & TextBox1.Text & "','" & tkhupd & "')"
command.ExecuteNonQuery()
MessageBox.Show(" Berjaya, Sila Masuk. ", "Tahniah", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MsgBox("exist")
End If
Else
MsgBox("Failed Login.")
End If
End While
Catch ex As Exception
End Try
End Sub
End Class
I am not sure what you are trying to do when there is not matching record in the database, but you don't have any code that would be hit in the case of no matching entries.
If there are no matching records, your while condition isn't met and nothing in the loop happens.
Fixing it likely involves rearranging the order of your loop and your if condition.
Check to see if data.hasRows first.
Example:
If data.HasRows() = True Then
While Data.Read
//code here for found rows
End While
Else
//code for no matching entries
End If
And as has been mentioned in Joel's comment, you really should look at using parameterized queries.
example of your insert command altered:
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES (?noK,?khupd)"
command.Parameters.AddWithValue("?noK",TextBox1.Text)
command.Parameters.AddWithValue("?khupd", tkhupd)
command.ExecuteNonQuery()

Simple VB Syntax to show some values from a database

Im very new to Visual Basic (using visual studio 2010). Im just doing some tests to connect to a mysql database.
I do not know how to call these values once I have made the sql query.
How do I go about this, i.e. to show the values on the labels on a form?
Code:
Imports MySql.Data.MySqlClient
Public Class Form1
Dim ServerString As String = "Server = localhost; User Id = root; database = CALIBRA"
Dim SQLConnection As MySqlConnection = New MySqlConnection
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()
MsgBox("Successfully connected to MySQL database.")
Else
SQLConnection.Close()
MsgBox("Connection is closed.")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub calibra_query(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("Records Successfully Retrieved")
SQLConnection.Dispose()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SQLStatement As String = "SELECT Auto1, Auto2, TotalWeight FROM txticket WHERE TicketCode = '12210'"
calibra_query(SQLStatement)
Dim Automobile1, Automobile2, TotalWgt As Long
SOMETHING MISSING HERE
SOMETHING MISSING HERE
Label2.Text = Automobile1.ToString()
Label2.Text = Automobile2.ToString()
Label2.Text = TotalWgt.ToString()
End Sub
End Class
What do I put in the "SOMETHING MISSING HERE"? Much appreciation.
You will need a data reader in order to read the content of what is returned from the sql query. Your Sub calibra_query, is executing a nonreader, that isn't going to do what you need. You only want to use executeNonReader for things that you don't need a result from. (Like an Update statement for example)
You want something a bit more like this:
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
End With
Dim myReader as MySqlDataReader = myCommand.ExecuteReader
If myReader.Read Then
TextBox1.Text = myReader.GetString(0)
TextBox2.Text = myReader.Getstring(1)
TextBox3.Text = myReader.GetInt32(2)
End If
myReader.Close()
SQLConnection.Close()
MsgBox("Records Successfully Retrieved")
SQLConnection.Dispose()
I am assuming the types of the 3 fields in your query, and just outputting it to text boxes to give you the idea. That also assumes that you are only going to get one record as a result.
(Edit: to fix formatting)