how to write update code vb.net and sql geeks - mysql

I wrote this update code for mysql server using vb.net and its not working.
Dim sqlstring = "Update initial_nom set f_name = '" &
TextBox1.Text & "',s_name = '" &
TextBox2.Text & "',th_name = '" &
TextBox3.Text & "',fo_name = '" &
TextBox4 & "',adm_type = '" &
ComboBox4.SelectedItem.ToString() & "'
where (app_no = " & TextBox5.Text & ")"
cmd.ExecuteNonQuery()

Try this:
Dim connectionString As String = "Server=my_server;Database=my_db;Uid=my_username;Pwd=my_password;"
Dim SQLConnection As New MySqlConnection(connectionString)
Dim SQLCommand As New MySqlCommand()
With SQLCommand
.CommandText = "UPDATE initial_nom SET f_name = #f_name, s_name = #s_name, th_name = #th_name, fo_name = #fo_name, adm_type = #adm_type WHERE app_no = #app_no"
.Connection = SQLConnection
.Parameters.AddWithValue("#f_name", TextBox1.Text)
.Parameters.AddWithValue("#s_name", TextBox2.Text)
.Parameters.AddWithValue("#th_name", TextBox3.Text)
.Parameters.AddWithValue("#fo_name", TextBox4.Text)
.Parameters.AddWithValue("#app_no", TextBox5.Text)
.Parameters.AddWithValue("#adm_type", ComboBox4.SelectedItem.ToString)
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
Don't forget to enter your own details in the connection string.
In answer to your other closed question, this should do what you want:
Dim connectionString As String = "Server=my_server;Database=my_db;Uid=my_username;Pwd=my_password;"
Dim SQLConnection As New MySqlConnection(connectionString)
Dim SQLCommand As New MySqlCommand()
With SQLCommand
.CommandText = "INSERT INTO nomination (f_name, s_name, th_name, fo_name, app_no, adm_type) values (#f_name, #s_name, #th_name, #fo_name, #app_no, #adm_type)"
.Connection = SQLConnection
.Parameters.AddWithValue("#f_name", TextBox1.Text)
.Parameters.AddWithValue("#s_name", TextBox2.Text)
.Parameters.AddWithValue("#th_name", TextBox3.Text)
.Parameters.AddWithValue("#fo_name", TextBox4.Text)
.Parameters.AddWithValue("#app_no", TextBox5.Text)
.Parameters.AddWithValue("#adm_type", ComboBox4.SelectedItem.ToString)
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
Update
I noticed in your other question that you were struggling with ADODB and a connection DSN, there is a far easier way to do this using the MySQL Connector.
Download and install the MySQL Connector from http://dev.mysql.com/downloads/connector/net/
You now need to add a reference to this in your project:
Select Browse and navigate to the Assemblies directory for the MySQL Connector:
Select MySQL.Data.dll and click Ok:
Now all you need to do is add Imports MySql.Data.MySqlClient to the very top of your form code and you will be able to access your database once you have created the correct connection string.
Here is some example code which will give you and idea of how you can perform some simple operations on your DB, this is tested and working (I was bored this morning!).
Imports MySql.Data.MySqlClient
Public Class Form1
Dim connectionString As String = "Server=my_server;Database=my_db;Uid=my_username;Pwd=my_password;"
Dim SQLConnection As New MySqlConnection(connectionString)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To 5
ComboBox4.Items.Add(i)
Next
ComboBox4.SelectedIndex = 0
End Sub
Private Sub update_row()
Dim SQLCommand As New MySqlCommand()
With SQLCommand
.CommandText = "UPDATE nomination SET f_name = #f_name, s_name = #s_name, th_name = #th_name, fo_name = #fo_name, adm_type = #adm_type WHERE app_no = #app_no"
.Connection = SQLConnection
.Parameters.AddWithValue("#f_name", TextBox1.Text)
.Parameters.AddWithValue("#s_name", TextBox2.Text)
.Parameters.AddWithValue("#th_name", TextBox3.Text)
.Parameters.AddWithValue("#fo_name", TextBox4.Text)
.Parameters.AddWithValue("#app_no", TextBox5.Text)
.Parameters.AddWithValue("#adm_type", ComboBox4.SelectedItem.ToString)
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Sub
Private Sub insert_row()
Dim SQLCommand As New MySqlCommand()
With SQLCommand
.CommandText = "INSERT INTO nomination (f_name, s_name, th_name, fo_name, app_no, adm_type) values (#f_name, #s_name, #th_name, #fo_name, #app_no, #adm_type)"
.Connection = SQLConnection
.Parameters.AddWithValue("#f_name", TextBox1.Text)
.Parameters.AddWithValue("#s_name", TextBox2.Text)
.Parameters.AddWithValue("#th_name", TextBox3.Text)
.Parameters.AddWithValue("#fo_name", TextBox4.Text)
.Parameters.AddWithValue("#app_no", TextBox5.Text)
.Parameters.AddWithValue("#adm_type", ComboBox4.SelectedItem.ToString)
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Sub
Private Sub select_from()
Dim SQLCommand As New MySqlCommand
Dim SQLAdapter As New MySqlDataAdapter
Dim DTable As New DataTable
With SQLCommand
.CommandText = "SELECT * FROM nomination"
.Connection = SQLConnection
End With
Try
SQLConnection.Open()
SQLAdapter.SelectCommand = SQLCommand
SQLAdapter.Fill(DTable)
DataGridView1.DataSource = DTable
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Sub
Private Sub create_table()
Dim SQLCommand As New MySqlCommand
With SQLCommand
.CommandText = "CREATE TABLE nomination (f_name varchar(50),s_name varchar(50),th_name varchar(50),fo_name varchar(50),app_no varchar(50),adm_type varchar(50))"
.Connection = SQLConnection
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Sub
Private Sub drop_table()
If MsgBox("Are you really sure you want to DROP this table?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Dim SQLCommand As New MySqlCommand
With SQLCommand
.CommandText = "DROP TABLE nomination"
.Connection = SQLConnection
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End If
End Sub
Private Sub truncate_table()
If MsgBox("Are you really sure you want to TRUNCATE this table?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Dim SQLCommand As New MySqlCommand
With SQLCommand
.CommandText = "TRUNCATE TABLE nomination"
.Connection = SQLConnection
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
create_table()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
drop_table()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
insert_row()
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
update_row()
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
select_from()
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
truncate_table()
End Sub
End Class
Here's the form I used, it needs Button1 - Button6, TextBox1 - TextBox5, ComboBox4 and a DataGridView control.
Hope this helps you out.

Related

Invalid attempt to access a field before calling Read() with MySql at answer.text = dr(1) or question.text =dr(3) when click get password

Imports MySql.Data.MySqlClient
Public Class Forgot_Password_form
Dim con As New MySqlConnection("host=localhost;username=root;password=system;database=bike")
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "select * from login where userid='" & useridtxt.Text & "'and question='" & question.Text & "'and answer='" & answertxt.Text & "'"
dr = cmd.ExecuteReader
If Not dr Is Nothing Then
dr.Read()
answer.Text = dr(1)
dr.Close()
End If
Catch ex As Exception
MessageBox.Show("UserID or answer is incorrect")
End Try
con.Close()
End Sub
Private Sub Exit__Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Exit_.Click
End
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Login_Menu.Show()
Me.Hide()
End Sub
Private Sub useridtxt_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles useridtxt.LostFocus
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "select * from login where userid='" & useridtxt.Text & "'"
dr = cmd.ExecuteReader
If Not dr Is Nothing Then
dr.Read()
question.Text = dr(3)
dr.Close()
End If
Catch ex As Exception
End Try
End Sub
End Class

Failed to insert data

I'm trying to add data to a MySQL Server database.
Here is the code:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As SqlConnection = New SqlConnection("Data Source=192.168.3.173\hidp;Initial Catalog=HIDP;Persist Security Info=True;User ID=intranet;Password=kikapu;APP=Intranet")
Dim sql As String = "Insert into [RAVARIAS].[StockMovimentos] ([CodHospital], [utilizador], [servico], [CodDevice], [CodConsumivel], [TipoMovimento], [DtMovimento], [Qtd]) values (#CodHospital, #utilizador, #servico, #CodDevice, #CodConsumivel, #TipoMovimento, #DtMovimento, #Qtd)"
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
cmd.Parameters.AddWithValue("#CodHospital", Session("Codhospital"))
cmd.Parameters.AddWithValue("#utilizador", TextBox1.Text)
cmd.Parameters.AddWithValue("#servico", TextBox2.Text)
cmd.Parameters.AddWithValue("#CodDevice", DropDownList3.SelectedItem)
cmd.Parameters.AddWithValue("#CodConsumivel", DropDownList4.SelectedItem)
cmd.Parameters.AddWithValue("#TipoMovimento", DropDownList2.SelectedItem)
cmd.Parameters.AddWithValue("#DtMovimento", Calendar1.SelectedDate)
cmd.Parameters.AddWithValue("#Qtd", TextBox4.Text)
connection.Open()
cmd.ExecuteNonQuery()
connection.Close()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox4.Text = ""
DropDownList2.ClearSelection()
DropDownList3.ClearSelection()
DropDownList4.ClearSelection()
Calendar1.SelectedDates.Clear()
End Sub
When I click on the button nothing happens.

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

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)