VB2013 & MySQL not talking properly and program freezing - mysql

I have been working on a small project for a while now - it takes a plain text input from an Ardiuno Board (simple text, only a few characters). It's a simple NFC Card tagging program. The program is supposed to take the input from the SerialPort and check the input text against a MySQL database. If it finds the name in the database, then it is to update one column, that's it.
The problem is two fold - first, while I can query the database and get a list of people within the database, the tagging side of the program will not update the database, not matter what input is passed to it. Second - whenever the program receives any input, the program locks up and the GUI becomes unresponsive.
My code is below, and I am happy for any Questions, Comments, or Criticisms. Yes, the MySQL server is on port '8228'. This code is driving me mad, and I apologize as it may seem messy...
Imports System.IO.Ports
Imports System.Threading
Imports System.Text
Imports System.Data.Odbc
Public Class Form1
Dim WithEvents SerialPort As New IO.Ports.SerialPort
Dim ListStr As String
Dim SQLString As String
Dim fstoday As String = Today.Day.ToString + "_" + Today.Month.ToString + "_" + Today.Year.ToString
Dim NextLine As String
Dim PortNum As String
Dim SqlConn As String
Dim sw As StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs)
Timer1.Start()
SerialPort.ReceivedBytesThreshold = 4
PortNum = "COM6"
SqlConn = "mydomain.local"
Call TestSQLConnectionToolStripMenuItem_Click()
Call ConnectSerial()
'create todays log file
Dim filesys As New FileStream("c:\TagLog\Log-" + fstoday + ".txt", FileMode.Append, FileAccess.Write, FileShare.Write)
filesys.Close()
End Sub
Private Sub ConnectSerial()
'set the USB (COM) Port and Bandwidth (BaudRate)
Try
SerialPort.BaudRate = 115200
SerialPort.PortName = PortNum
SerialPort.Open()
LabPort.Text = "Reader OK"
LabPort.ForeColor = Color.Green
Catch
SerialPort.Close()
LabPort.Text = "Reader Not Found"
LabPort.ForeColor = Color.Red
End Try
End Sub
'This handles setting and reading from the serial port
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Dim str As String = SerialPort.ReadExisting()
Invoke(myD1, str)
End Sub
'This makes the serial input into String format
Delegate Sub myMethodDelegate(ByVal [text] As String)
Dim myD1 As New myMethodDelegate(AddressOf myShowStringMethod)
Sub myShowStringMethod(ByVal myString As String)
ListStr = ""
SQLString = ""
'display text to our textbox
TextBox2.AppendText(myString)
'Add the last input to the listbox
ListBox1.Items.Add(TextBox2.Text)
ListStr = ListBox1.Items(ListBox1.Items.Count - 1)
SQLString = "Select * From TagTable where QuickName='" + myString + "';"
Try
Dim cn As OdbcConnection = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Dim cmd As New OdbcCommand(SQLString, cn)
SQLString = "UPDATE tagtable SET State = NOT State, Time=Now() WHERE QuickName='" + myString + "';"
sw.WriteLine(vbCr + Now() + " " + myString)
Call UpdateSQL()
cn.Close()
Catch ex As Exception
sw.WriteLine(vbCr + Now() + ex.ToString)
End Try
sw.Close()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Once per Tick, check what the COM port is saying.
If SerialPort.IsOpen Then
TextBox2.Text = ""
Else
TextBox2.Text = ""
Call ConnectSerial()
End If
End Sub
Private Function IIf(fileExists As Boolean, p2 As String) As Object
Throw New NotImplementedException
End Function
Private Sub UpdateSQL()
Dim cn As OdbcConnection = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
'check connection to the SQL Server and update the records
Dim cmd As OdbcCommand = New OdbcCommand(SQLString, cn)
cn.Open()
LabSQL.ForeColor = Color.Green
LabSQL.Text = "SQL OK"
If SQLString <> "" Then
Try
cmd.ExecuteNonQuery()
cn.Close()
LabSQL.ForeColor = Color.Green
Catch ex As Exception
LabSQL.ForeColor = Color.Red
LabSQL.Text = "SQL Not OK"
sw.WriteLine(vbCr + Now() + " " + ex.ToString)
cn.Close()
End Try
Else
cn.Open()
LabSQL.ForeColor = Color.Green
End If
'If there is a problem, change Sql Label, and clsoe the error'd connection.
cn.Close()
SQLString = ""
End Sub
Private Sub TestSQLConnectionToolStripMenuItem_Click() Handles TestSQLConnectionToolStripMenuItem.Click
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
'check connection to the SQL Server
Try
cn.Open()
LabSQL.ForeColor = Color.Green
LabSQL.Text = "SQL OK"
cn.Close()
'If there is a problem, change Sql Label, display the error in a message box and Close the error'd connection.
Catch ex As OdbcException
LabSQL.ForeColor = Color.Red
LabSQL.Text = "SQL Not OK"
cn.Close()
End Try
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Dim msgans As String
msgans = MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo, "Exit?")
If msgans = vbYes Then
SerialPort.Close()
Me.Close()
End If
End Sub
Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click
PortNum = "COM1"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
PortNum = "COM2"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem5_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem5.Click
PortNum = "COM3"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem6_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem6.Click
PortNum = "COM4"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem7_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem7.Click
PortNum = "COM5"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem8_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem8.Click
PortNum = "COM6"
Call ConnectSerial()
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
MsgBox("Made by Phill C at Epoq IT. Tag Control V2.3")
End Sub
Private Sub LocalMachineToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LocalMachineToolStripMenuItem.Click
SqlConn = "localhost"
Call TestSQLConnectionToolStripMenuItem_Click()
End Sub
Private Sub OtherLocationToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OtherLocationToolStripMenuItem.Click
SqlConn = InputBox("Enter the SQL Address or Location.", "SQL Location Input", "localhost").ToString
Call TestSQLConnectionToolStripMenuItem_Click()
End Sub
Private Sub ShowUserListToolStripMenuItem_Click() Handles ShowUserListToolStripMenuItem.Click
Dim cn As OdbcConnection
Dim Outstring As String = ""
SQLString = "Select Person,Quickname from TagTable"
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Dim cmd As New OdbcCommand(SQLString, cn)
Dim Query = cmd.ExecuteReader()
Outstring = "FULL NAME, QUICK NAME" + vbCr
While Query.Read
Outstring = Outstring + Query.Item(0) + " , " + Query.Item(1) + vbCr
End While
MsgBox(Outstring)
Query.Close()
cn.Close()
End Sub
Private Sub AddUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddUserToolStripMenuItem.Click
Dim QueryFull = InputBox("Enter the New Users Full Name.", "New User Input", "New User").ToString
Dim QueryQName = InputBox("Enter the New Users Quick Name / Nickname.", "New User Input", "New User").ToString
SQLString = "Insert Into TagTable (QuickName,Person,State,Time) Values ('" + QueryQName + "','" + QueryFull + "','In', NOW());"
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Try
Dim cmd As New OdbcCommand(SQLString, cn)
MsgBox("New User has been setup on the Server.")
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox("New User setup has failed, please contact IT Support")
End Try
End Sub
Private Sub DeleteUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteUserToolStripMenuItem.Click
Dim QueryFull = InputBox("Enter the Users Full Name.", "Delete User Input", "User To be deleted").ToString
Dim QueryQName = InputBox("Enter the Users Quick Name / Nickname.", "Delete User Input", "User To be deleted").ToString
SQLString = "Delete From TagTable Where QuickName='" + QueryQName + "' AND Person='" + QueryFull + "';"
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Try
Dim cmd As New OdbcCommand(SQLString, cn)
MsgBox("User has been removed from the Server.")
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox("User revomal has failed, please check the full name and quick names, and try again.")
End Try
End Sub
End Class

Related

Remote database connection in VB.net not working

I'm currently working on a MySQL connection in my VB.net app. I have a form which has the following code:
Imports System.Data
Imports System.Data.SqlClient
Public Class Form4
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ConnectToSQL()
End Sub
Private Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Password As String
Dim Password2 As String
Dim userName As String
Try
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT user_username, user_pass FROM users WHERE (user_username = '" & txtUsername.Text & "' ) AND (user_pass = '" & txtPassword.Text & "')"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
Password = lrd("Password").ToString()
userName = lrd("UserName").ToString()
Password2 = txtPassword.Text()
If Password = Password2 And userName = txtUsername.Text Then
MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
)
Form2.Show()
Me.Hide()
txtPassword.Text = ""
txtUsername.Text = ""
End If
End While
Else
MessageBox.Show("Username or Password incorrect...", "Authentication Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtPassword.Text = ""
txtUsername.Text = ""
End If
End If
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
Everytime I run the application, I enter the login details correctly and click on the sign in button (Button2). The problem is, it doesn't do anything. It doesn't throw an exception, doesn't even try to login to the server as far as I can tell. I replaced the login details with that of my own server, so that's not the problem. Did I miss something?
Don't store passwords in clear-text!
Furthermore your code is prone to sql incjection.
Nothing happens because this If will never be true:
...
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
...

MySQL login works for me but not my friend using VB

I have a program that takes info from the user and logs them into a database using Phpmyadmin, our code is the exact same, except for my friend he can't login.
Code is here:
Both our database name, tables and columns are the EXACT same, he can register the account to the DB so it stores it, but when he tries to login with the same information it says that it was unsuccessful.
SignUpForm(THIS WORKS)
Public Class frmSignup
Dim ServerString As String = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MsgBox("Successfully connected to DB")
Else
SQLConnection.Close()
MsgBox("Failed to connect to DB")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveAccountInformation(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
SQLConnection.Dispose()
End Sub
Private Sub btnSignup_Click(sender As Object, e As EventArgs) Handles btnSignup.Click
If txtPasswd.Text = txtPasswd2.Text Then
MessageBox.Show("Passwords Match!")
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()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(txtPasswd.Text)))
End Using
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & "','" & HashedPass & "')"
SaveAccountInformation(SQLStatement)
MessageBox.Show("Account Successfully Registered")
frmLogin.Show()
frmLoginScreen.Hide()
Else
MessageBox.Show("Passwords Do Not Match!")
txtPasswd.Text = Focus()
txtPasswd.Clear()
txtPasswd2.Text = Focus()
txtPasswd2.Clear()
End If
End Sub
End Class
LOGIN FORM(THIS DOES NOT WORK FOR HIM BUT IT WORKS FOR ME)
Imports MySql.Data.MySqlClient
Imports System.Security.Cryptography
Public Class frmLogin
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim conStr = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQL = "SELECT * FROM accountinfodb WHERE Usernames = #uname AND `Passwords` = #pword"
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()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(txtPasswd.Text)))
End Using
' this object will be closed and dispose # End Using
Using dbCon As New MySqlConnection(conStr)
' the command object likewise
Using cmd As New MySqlCommand(SQL, dbCon)
dbCon.Open()
cmd.Parameters.Add(New MySqlParameter("#uname", txtUsername.Text))
cmd.Parameters.Add(New MySqlParameter("#pword", HashedPass))
' create a Using scope block for the reader
Using rdr As MySqlDataReader = cmd.ExecuteReader
If rdr.HasRows Then
MessageBox.Show("Welcome, " & txtUsername.Text)
frmProduct.Show()
Else
MessageBox.Show("Oops! Login unsuccessful!(Password/Username may be wrong, or the user may not exist!")
txtUsername.Clear()
txtUsername.Focus()
txtPasswd.Clear()
End If
End Using
End Using ' close/dispose command
End Using ' close/dispose connection
End Sub
End Class
WOULD ALSO LIKE TO MENTION
I shared my files over google drive with him, so he did not copy and paste any of the code. This is the exact same files from MY computer.
Ok I found the issue, he was using an outdated version of MySQL while my version was the most up to date. I reinstalled the proper MySQL server to the newest version and it worked!

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

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

error when update data ms access using visual basic 2010

**i have simple application, but i dont know how to fix it.
this pic when i try to edit my database--> http://i861.photobucket.com/albums/ab171/gopak/sa_zps5a950df5.jpg
when i click button edit i want my access data will be update.this is my code..
thanks for your advice**
Imports System.Data.OleDb
Public Class Form2
Public cnstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Gop's\Downloads\admin site\admin site\admin site\bin\Debug\data_ruangan.accdb"""
Public cn As New OleDbConnection
Public cmd As New OleDbCommand
Public adaptor As New OleDbDataAdapter
Private Sub logout_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles logout_btn.Click
Form1.Show()
Me.Close()
End Sub
Private Sub exit_btn_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exit_btn.Click
Dim a As Integer
a = MsgBox("Are you sure want to exit application?", vbInformation + vbYesNo, "Admin Site Virtual Tour Application")
If a = vbYes Then
End
Else
Me.Show()
End If
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Data_ruanganDataSet.data_ruangan' table. You can move, or remove it, as needed.
Me.Data_ruanganTableAdapter.Fill(Me.Data_ruanganDataSet.data_ruangan)
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i = DataGridView1.CurrentRow.Index
Label7.Text = DataGridView1.Item(0, i).Value
txtName.Text = DataGridView1.Item(1, i).Value
txtLocation.Text = DataGridView1.Item(2, i).Value
txtCapacity.Text = (DataGridView1.Item(3, i).Value).ToString
txtOperational.Text = (DataGridView1.Item(4, i).Value).ToString
txtInformation.Text = DataGridView1.Item(5, i).Value
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'If txtName.Text <> "" And txtLocation.Text <> "" And txtCapacity.Text <> "" And txtOperational.Text <> "" And txtInformation.Text <> "" Then
Dim i = DataGridView1.CurrentRow.Index
Dim ID = DataGridView1.Item(0, i).Value
Dim cmd As New OleDb.OleDbCommand
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
cmd.Connection = cn
cmd.CommandText = ("update data_ruangan set Name = '" & txtName.Text & _
"',Location = '" & txtLocation.Text & "',Capacity = '" & txtCapacity.Text & _
"',Operational_Hours ='" & txtOperational.Text & "',Information = '" & txtInformation.Text & ";")
cmd.ExecuteNonQuery()
cn.Close()
txtName.Text = ""
txtLocation.Text = ""
txtCapacity.Text = ""
txtOperational.Text = ""
txtInformation.Text = ""
'End If
End Sub
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
End Class
Try to use a parameterized query to execute your code. The error message is relative to the fact that you haven't initialized your connection with the information contained in the ConnectionString.
Here an example on how to do that...... but......
Dim cmdText = "update data_ruangan set [Name] = ?,Location = ?,Capacity = ?, " & _
"Operational_Hours =?,Information = ?;"
Using cn = new OleDbConnection( cnstring )
Using cmd = OleDb.OleDbCommand(cmdText, cn)
cn.Open
cmd.Parameters.AddWithValue("#p1", txtName.Text)
cmd.Parameters.AddWithValue("#p2", txtLocation.Text)
cmd.Parameters.AddWithValue("#p3", txtCapacity.Text)
cmd.Parameters.AddWithValue("#p4", txtOperational.Text)
cmd.Parameters.AddWithValue("#p5", txtInformation.Text)
'''' WARNING ''''
' WITHOUT A WHERE STATEMENT YOUR QUERY WILL UPDATE
' THE WHOLE TABLE WITH THE SAME VALUES
'''' WARNING ''''
cmd.ExecuteNonQuery()
End Using
End Using
txtName.Text = ""
txtLocation.Text = ""
txtCapacity.Text = ""
txtOperational.Text = ""
txtInformation.Text = ""
This code updates all the records of your table with the same value, so, unless you have only one record and update Always the same record you need to add a WHERE condition to your command.
Also, the NAME word is a reserved keyword in Access 2007/2010 and it is better to encapsulate that word with square brackets to avoid a syntax error message.
I have also removed the global variable OleDbConnection and used a local one that will be closed and destroyed when the code exits from the Using statement. This is the correct way to handle disposable objects, in particular every connection object is Always to be used in this way to release as soon as possible the expensive unmanaged resource used by the object.