Updating MySQL database in xampp using Visual Studio or Visual Basic - mysql

I tried everything that I can do - I'm a beginner at programming. I wanted to update my database in xampp using VB or Visual Studio but can't seem to do it.
This is my code for that form.:
Imports MySql.Data.MySqlClient
Public Class Form4
Public MysqlConn As MySqlConnection
Public cmd As New MySqlCommand
Public da As New MySqlDataAdapter
Public Sub MysqlConnection()
MysqlConn = New MySqlConnection()
'Connection String
MysqlConn.ConnectionString = "server=localhost;" _
& "user id=root;" _
& "password=;" _
& "database=bank"
'OPENING THE MysqlConnNECTION
MysqlConn.Open()
End Sub
Public Sub add()
Dim sql As String
Dim TempTable As New DataTable
sql = "update cbank set Balance = Balance + " & TextBox2.Text & "where AccountID = " & TextBox1.Text & "and PIN = " & TextBox3.Text & ";"
'bind the connection and query
With cmd
.Connection = MysqlConn
.CommandText = sql
End With
da.SelectCommand = cmd
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConnection()
add()
End Sub
End Class
There is no error it just that there is no output also

Keep you data objects local so you can be sure they are closed and disposed. A Using...End Using block ensures this even if there is an error. You can make your connection string a form level variable so you can use it anywhere but that is the only form level variable you need.
You can pass your connection string directly to the constructor of the connection.
You can pass your sql command text and the connection directly to the constructor of the command.
Please always use Parameters. Not only wil it save you from misplacing quotes but it will help ensure that correct datatypes are sent to the database. The most important thing is it helps protect you database from sql injection which can destroy your database. I had to guess at the datatypes in your database. Check the database and adjust the code accordingly.
Private ConnString As String = "server=localhost;user id=root;password=;database=bank"
Private Sub add()
Using cn As New MySqlConnection(ConnString)
Using cmd As New MySqlCommand("update cbank set Balance = Balance + #Balance where AccountID = #ID and PIN = #PIN;", cn)
cmd.Parameters.Add("#Balance", MySqlDbType.Decimal).Value = CDec(TextBox2.Text)
cmd.Parameters.Add("#ID", MySqlDbType.Int32).Value = CInt(TextBox1.Text)
cmd.Parameters.Add("#PIN", MySqlDbType.Int32).Value = CInt(TextBox3.Text)
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub

Quotes problem.
Imports MySql.Data.MySqlClient
Public Class Form4
Public MysqlConn As MySqlConnection
Public cmd As New MySqlCommand
Public da As New MySqlDataAdapter
Public Sub MysqlConnection()
MysqlConn = New MySqlConnection()
'Connection String
MysqlConn.ConnectionString = "server=localhost;" _
& "user id=root;" _
& "password=;" _
& "database=bank"
'OPENING THE MysqlConnNECTION
MysqlConn.Open()
End Sub
Public Sub add()
Dim sql As String
Dim TempTable As New DataTable
sql = "update cbank set Balance = Balance + " & TextBox2.Text & "where AccountID = " & TextBox1.Text & "and PIN = " & TextBox3.Text & ";"
bind the connection and query
With cmd
.Connection = MysqlConn
.CommandText = sql
End With
da.SelectCommand = cmd
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Hide()
Form2.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConnection()
add()
End Sub
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class

Related

vb.net(Additional information: Unknown column 'Secret_question' in 'where clause')

Imports MySql.Data.MySqlClient
Public Class Forgot_password
Private Sub GroupBox1_Enter(sender As Object, e As EventArgs) Handles GroupBox1.Enter
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New MySqlConnection("host=localhost;username=root; password=godzilla408421;database=program")
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM program.login where Username ='" & useridtxt.Text & "' and Secret_question='" & questiontxt.Text & "' and answer='" & answertxt.Text & "'"
dr = cmd.ExecuteReader <<<<(HERE IS MY PROBLEM,IT TELLS ME THAT,"UNKNOW COLUMN'SECRET_QUESTION IN WHERE CLAUSE',PLEASE PLEASE PLEASE HELP"0>>>>
If Not dr Is Nothing Then
dr.Read()
passwordtxt.Text = dr(1)
dr.Close()
Else
MsgBox("Usename or password doesnt match")
End If
End Sub
End Class
First check your table whether you have Secret_question field or not, maybe you put it plural like Secret_questions. Then it's better to modify your code a bit like the following
cmd.CommandText = "SELECT * FROM program.login where Username =?Username and Secret_question=?Secret_question and answer=?answer;"
cmd.Parameters.AddWithValue("?Username", useridtxt.Text.Trim())
cmd.Parameters.AddWithValue("?Secret_question", questiontxt.Text.Trim())
cmd.Parameters.AddWithValue("?answer", answertxt.Text.Trim())
dr = cmd.ExecuteReader

Having trouble encrypting my MySQL password as MD5 hash from VB.net

I'm trying to hash the password the user enters into my DB as MD5, and I'm having trouble with it. I know MD5 is not as secure as it was before, and now not with salting, this is just for testing purposes and in no way am I actually deploying this for people to use. It's just for fun! The username gets entered into the database but the password doesn't. Here is my code:
Imports MySql.Data.MySqlClient
Imports System.Security.Cryptography
Imports System.Text
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()
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
I think I possibly added the wrong value in my SQL Query, but if I add txtPasswd, I'm not sure where I'd put the HashedPass variable into my code?
The answer to your question is found with basically the same code here:
VB.NET login with a MySQL database
Direct link to answer:
https://stackoverflow.com/a/22939770/1475285
As mentioned by Bread102, you're not assigning the hash function result to your variable. The below should work in your case
Dim HashedPass As String = ""
Using MD5hash As MD5 = MD5.Create()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHashSystem.Text.Encoding.ASCII.GetBytes(txtUsername.Text)))
End Using
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & "','" & HashedPass & "')"

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!

InvalidOperationException ocurred

I am trying to access MySql database but get this error:
Exception thrown: 'System.InvalidOperationException' in MySql.Data.dll
Additional information: The CommandText property has not been properly initialized.
This Would be my Code
Imports MySql.Data.MySqlClient
Public Class Login
Dim cn As New MySqlConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cn.ConnectionString = "server=localhost; userid=root; password=root; database=pos"
cn.Open()
MsgBox("Connected")
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
cn.Close()
Dim myadapter As New MySqlDataAdapter
Dim sqlquery = "SELECT * from pos.values where username='" & txtUsername.Text & "' AND password='" & txtPassword.Text & "'"
Dim mycommand As New MySqlCommand
mycommand.Connection = cn
cn.Open()
myadapter.SelectCommand = mycommand
Dim mydata As MySqlDataReader
mydata = mycommand.ExecuteReader
If mydata.HasRows = 0 Then
Beep()
MsgBox(txtUsername.Text & " Invalid")
Else
MsgBox("Welcome " & txtUsername.Text)
MainWindow.Show()
Me.Hide()
cn.Close()
End If
End Sub
End Class
Just like the error says, you never set the CommandText property of the MySqlCommand object. You've defined a SELECT query, but never use it anywhere. Set it on the command object before trying to use that object:
mycommand.CommandText = sqlquery
Note: Be aware that your code is wide open to SQL injection attacks. You should use query parameters instead of directly executing user input as code. Basically, you're allowing users to execute any code they want on your database.
Also: You are storing user passwords in plain text. This is grossly irresponsible to your users. If you can read their password, so can an attacker. User passwords should be obscured with a 1-way hash so that they can never be read, not even by you as the system owner.

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