Connecting to a Online MySQL Database using VB.Net - mysql

I've searched around and haven't been able to find anything along the lines of doing this.

You need to install Connector/Net, which will give you a full ADO.Net provider for MySql you can use. Be warned that this is GPL software, meaning if you distribute it as part of a commercial product you must also distribute your source code. It's an open legal question, but last I heard most web sites are okay with this, because you are not distributing your server code. Desktop apps may have an issue, though.

Imports System.Data.SqlClient
Imports MySql.Data.MySqlClient
Public Class LoginForm1
Dim MySQLConnection As MySqlConnection
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Close()
End Sub
Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Close()
End Sub
Private Sub Cancel_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
End
End Sub
Private Sub OK_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
MySQLConnection = New MySqlConnection
MySQLConnection.ConnectionString = "server=db4free.net;Port=3306; User ID=db4freeusername; password=db4freepassword; database=nameofyourdatabase"
MySQLConnection.Open()
Dim MyAdapter As New MySqlDataAdapter
Dim SqlQuary = "SELECT * From nameofthetable WHERE Username='" & UsernameTextBox.Text & "' AND password = '" & PasswordTextBox.Text & "';"
Dim Command As New MySqlCommand
Command.Connection = MySQLConnection
Command.CommandText = SqlQuary
MyAdapter.SelectCommand = Command
Dim Mydata As MySqlDataReader
Mydata = Command.ExecuteReader
If Mydata.HasRows = 0 Then
MsgBox("Error During Login:Please Enter Valid Data")
Else
Form1.Show()
Me.Hide()
End If
End Sub
End Class

First of all you need to install MySQL connector for .NET.
Imports MySql.Data.MySqlClient
Dim myConnection As MySqlConnection = New MySqlConnection()
Dim myConnectionString As String = "Server=SERVERNAME;Database=DATABASE;Uid=root;Pwd=password;"
myConnection.ConnectionString = myConnectionString
myConnection.Open()
//execute queries, etc
myConnection.Close()

I use C#:
const String ConnectionString = "Driver={MySQL ODBC 5.1 Driver};Server=localhost;Port=3306;Database=test;User=root;Password=;Option=3;";
OdbcConnection conn = new OdbcConnection(ConnectionString);
conn.Open();
OdbcCommand command = new OdbcCommand();
command.CommandType = CommandType.StoredProcedure;
command.Connection = conn;
command.CommandText = "insert into search (tempsearchKey, state, suburb) values ('" + tempsearchKey+"','"+state+"','"+suburb+"')";
command.ExecuteNonQuery();
command.Cancel();
install odbc driver from mysql website
and convert this to VB.NET,
Maybe this link could help:
http://dev.mysql.com/tech-resources/articles/ebonat-load-and-search-mysql-data-using-vbnet-2005.html

Install MySQL connector for .NET, and APACHE, also install XAMPP so you could use phpMyAdmin

Related

How to connect datagrid and mysql database through adodb

I have to display a table in data grid in vb.net(visual studio 2008) using adodb from mysql.
but the following code not working .(No error are shown)
please help
I opted adodb due to error,even after many attempts ,using mysqldataadpter
Imports MySql.Data.MySqlClient
'Imports MySql.Data.Types
'Imports MySql.Data.VisualStudio
'Imports MySql.Data
Imports System.IO
Imports System.Data
Imports CrystalDecisions.CrystalReports.Engine
Public Class Form3
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim mrs2 As New ADODB.Recordset
Dim DBPath As String, sconnect As String
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sconnect = "DRIVER={MySQL ODBC 8.0 Unicode Driver};Server=localhost;Database=stockauto;User=root;Password=;"
If Conn.State = 1 Then
Conn.Close()
End If
Conn.Open(sconnect)
sql2 = "SELECT * From STOCK"
mrs.Open(sql2, Conn)
If mrs.State = 1 Then
mrs.Close()
End If
mrs.Open(sql2, Conn)
DataGridView1.DataSource = mrs
DataGridView1.Refresh()
End Sub
First the connection string. See https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/
I used the simplest example. Replace yourUserID and yourPassword with the real values.
Get rid of all the ADODB and ODBC stuff. This code uses ADO.net
Using...End Using blocks ensure that database objects are closed and disposed.
Private MySqlConnStr As String = "Server=localhost;Database=stockauto;Uid=yourUserId;Pwd=yourPassword;"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetStockData()
DataGridView1.DataSource = dt
End Sub
Private Function GetStockData() As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(MySqlConnStr),
cmd As New MySqlCommand("SELECT * From STOCK", cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
ADODB is the old mechanism from pre-.Net VB. It exists only for backwards compatibility with old code and should not be used for new development.
Try this, which uses the updated ADO.Net:
' Don't use the root account to connect to the database!
Private sconnect As String = "DRIVER={MySQL ODBC 8.0 Unicode Driver};Server=localhost;Database=stockauto;User=root;Password=;"
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim data As New DataTable
Using cn As New MySqlConnection(sconnect), _
cmd As New MySqlCommand("SELECT * FROM Stock", cn), _
da As New MySqlDataAdapter(cmd)
da.Fill(data)
End Using
DataGridView1.DataSource = data
DataGridView1.Refresh()
End Sub

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!

Connect to mySQL with VB.NET from values

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

access a mysql db and displaying it in a gridview or table

I am trying to access a Mysql DB and display it in a Gridview in .Net
I can get it to connect to the DB, but it displays nothing and there is records in the DB, this is the code i am using.
Dim MysqlConn As MySqlConnection
Dim ContactsCommand As New MySqlCommand
Dim ContactsAdapter As New MySqlDataAdapter
Dim ContactsData As New DataTable
Dim SQL As String
Private Sub btnGrabData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabData.Click
MysqlConn = New MySqlConnection()
SQL = "SELECT AffID FROM toutcome"
MysqlConn.ConnectionString = "Server=localhost;Database=merrywoodtest;UID=MerryWoodTest;PWD=H0r$hamTest;"
Try
MysqlConn.Open()
ContactsCommand.Connection = MysqlConn
ContactsCommand.CommandText = SQL
ContactsAdapter.SelectCommand = ContactsCommand
ContactsAdapter.Fill(ContactsData)
DataGridView1.DataSource = ContactsData
Catch myerror As MySqlException
MessageBox.Show("Cannot connect to database: " & myerror.Message)
Finally
MysqlConn.Close()
End Try
End Sub
Please make sure that you will call DataBind() method of DataGridView after the data source is assinged.
You may also set the Connection property of the ContactsCommand object and the SelectCommand property of the ContactsAdapter object.

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)