Connect to mySQL with VB.NET from values - mysql

Im trying to connect to mySql, but I have problem locating where im doing wrong.
My form contain e a label that is a number thats going to be posted to Score and a textbox where the user typed their name to be posted in Navn.
My code so far is:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim connect As New SqlConnection("Data Source = mysqlAdress;Network Library= DBMSSOCN;Initial Catalog=**;User ID=**;Password=**;")
Dim query As String = "INSERT INTO 2048 VALUES(#score, #name)"
Dim command As New SqlCommand(query, connect)
command.Parameters.Add("#score", SqlDbType.Int).Value = Label1.Text
command.Parameters.Add("#navn", SqlDbType.VarChar).Value = TextBox1.Text
connect.Open()
connect.Close()
End Sub

Your table name should be enclosed in backticks like this:
Dim query As String = "INSERT INTO `2048` VALUES(#score, #name)"
Also try to avoid table names with such naming conventions ie., only numbers.
Also you are opening and closing the connection simultaneously.
connect.Open()
connect.Close()
Try like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim connectionString As String = "Data Source = mysqlAdress;Network Library= DBMSSOCN;Initial Catalog=**;User ID=**;Password=**;"
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
With sqlCommand
.CommandText = "INSERT INTO `2048` VALUES(#score, #name)"
.Connection = SQLConnection
.CommandType = CommandType.Text
.Parameters.AddWithValue("#score", Label1.Text)
.Parameters.AddWithValue("#name", TextBox1.Text)
End With
Try
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox ex.Message.ToString
Finally
SQLConnection.Close()
End Try
End Using
End Using
End Sub

Related

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!

key word not supported 'data source'

im having problem in my connection. the error said that key word not supported in the data source and i dont what to do next. thanks in advance!
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class frmMasancayClinicSignupvb
Dim connection As New MySqlConnection
Dim myReader As MySqlDataReader
Dim Adapter As MySqlDataAdapter
Dim myCommand As MySqlCommand
Dim Dset As New DataSet
Dim table As New DataTable
Dim MyQuery As String
Dim i As Integer
Private Sub frmMasancayClinicSignupvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connection = New MySqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mark\Documents\MASANCAYCLINICLOGIN.mdf;Integrated Security=True;Connect Timeout=30")
Try
If connection.State = ConnectionState.Closed Then
connection.Open()
MsgBox("connected to database")
Else
connection.Close()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub
End Class
It appears that you're passing in the arguments for a SqlConnectionStringBuilder - that's for Microsoft's SqlServer database, not MySql. (see
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.integratedsecurity(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2 ).
MySqlConnection takes "Data Source" but doesn't take those other parameters. See :
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html#connector-net-examples-mysqlconnection-defctor

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

How to delete database records in phpmyadmin?

I am new in VB.net, sql and even phpmyadmin gui. I want to delete records saved in my phpmyadmin but I got an error when executing sqlcommand's executenonquery()
This is my code used in VB.NET:
Public Sub RetrieveInfos(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)
lblAge.Text = myReader.GetString(1)
End If
myReader.Close()
SQLConnection.Close()
MsgBox("Records Successfully Retrieved")
SQLConnection.Dispose()
End Sub
Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
Dim SQLStatement As String = "DELETE FROM patient WHERE 1"
RetrieveInfos(SQLStatement)
End Sub
Any help would be appreciated. Thanks!
To delete data from phpmyadmin, As specified in phpMyAdmin setting that you need to edit in config.inc.php.
boolean $cfg['AllowUserDropDatabase'] (line 503)
show a 'Drop database' link to normal users

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)