vb.net application login using mysql database - mysql

im trying to let users login to an application i created in vb.net using the user table of the application's database in mysql
i heard that The usual way to do this is to have just one MySQL user called "[my_app_name]" with the relevant permissions. Then my application uses it's own user table to control access to the application, and the one MySQL user to access the database. but i dont know how to do it, can someone please help me with it. im new to all this.
thanks

If you're making a login form that will check for authetication with users and their passwords on a MySQL database just follow this code I wrote for my own login form.
Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
Dim conn As MySqlConnection
'Connect to the database using these credentials
conn = New MySqlConnection
conn.ConnectionString = "your server goes here; user id=userid goes here; password=self explanatory; database=the database where the credential information is located"
'Try and connect (conn.open)
Try
conn.Open()
Catch myerror As MySqlException 'If it fails do this... (i.e. no internet connection, etc.)
MsgBox("Error connecting to database. Check your internet connection.", MsgBoxStyle.Critical)
End Try
'MySQL query (where to call for information)
Dim myAdapter As New MySqlDataAdapter
'Tell where to find the file with the emails/passes stored
Dim sqlquery = "SELECT * FROM your database with info WHERE Email = '" & txtEmail.Text & "' AND Password = '" & txtPassword.Text & "'"
Dim myCommand As New MySqlCommand
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'Start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
'See if the user exists
If myData.HasRows = 0 Then
MsgBox("Invalid email address or password.", MsgBoxStyle.Critical)
'Insert your settings change here. (i.e. My.Settings.LoggedIn = False)
Else
MsgBox("Logged in as " & txtEmail.Text & ".", MsgBoxStyle.Information)
'Another settings change: My.Settings.LoggedIn = True
Me.Close() 'close the login form
End If
Be sure to change the control names and also add a setting.

Open up MySQL Workbench and towards the bottom right of the first screen, under the "Server Administration" column, you'll see "Manage Security". Click on that. In the menu to the left you will see "Users and Privileges". Click on that. You'll see a button that says "Add Account" which, when clicked, will allow you to create a new user. In the Schema Privileges tab you can modify the user's permissions.
The user you created here can be used in your connection string. Here is an example MySQL connection string from one of my applications. The username in the connection string below, repair, was created with "Login Name:" as "repair" and "Limit Connectivity to Hosts Matching:" as "%".
"Server=10.0.0.113;uid=repair;pwd='password&92';database=repair"
I hope this helps. Have a great day.

Related

VB.Net with Mysql A connection attempt failed..." error arise when trying to read data from Mysql table. Insert into statement is working

I'm new to Mysql databases. I created and connected successfully a database for the local server. But "A connection attempt failed..." error arise when trying to read data from a table. "Insert into ..." statement is working. I searched for whole web for the reason. Not success. Anyone can help, please. Thank in advance...
Complete error description:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Relevant Code as follows:
following function Working and Connected successfully
Public Function Connect() As Boolean
Dim Status As Boolean
Try
conn.ConnectionString = "Server=" & Server & ";Port=3306;Database=" & DBName & ";User ID=" & UID & ";Password=" & Pwd & ";CharSet=utf8;"
conn.Open()
cmd.Connection = conn
If conn.State = ConnectionState.Open Then
Status = True
End If
Catch ex As Exception
ErrorMsg = ex.Message
Status = False
End Try
Return Status
End Function
Following Function returns the error...
Public Function getData(ByVal SQLStr As String) As MySql.Data.MySqlClient.MySqlDataReader
Dim tmpDR As MySql.Data.MySqlClient.MySqlDataReader
If conn.State = ConnectionState.Open Then
cmd.CommandText = SQLStr
tmpDR = cmd.ExecuteReader()
Else
MsgBox("Database not connected...", MsgBoxStyle.Exclamation, "Connection Error")
tmpDR = Nothing
End If
getData = tmpDR
End Function
Get rid of any class level database objects. Get rid of the Function Connect altogether. If you ever start to write
If conn.State = ConnectionState.Open Then
you should know you are doing it wrong.
Don't pass DataReader's around. The connection must remain open for them to function. Load a DataTable and pass that after the connection and command are disposed by the Using block.
If you intend to show a message box to the user, let exceptions bubble up to the user interface code.
Private ConStr As String = "Server=" & Server & ";Port=3306;Database=" & DBName & ";User ID=" & UID & ";Password=" & Pwd & ";CharSet=utf8;"
Public Function getData(ByVal SQLStr As String) As DataTable
Dim dt As New DataTable
Using conn As New MySqlConnection(ConStr),
cmd As New MySqlCommand(SQLStr)
conn.Open
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
As you can see, it only takes one simple line to create a connection. Connections are precious resources and should only be opened directly before the .Execute... and closed as soon as possible.

MySQL connection failing "user#LAPTOP..." (using password: NO)

I'm an absolute beginner in MySQL and trying to build a connection to my Visual Basic program. I use XAMPP and created a new user (admin) with a password. When I try to make the connection, it fails instead of using the right password.
I installed .NET Connector and ODBC Connector and imported the MySQL dll.
If you're able to help me, please answer as detailed as possible.
Private Sub btn_KI_Anzeigen_Click(sender As Object, e As EventArgs) Handles btn_KI_Anzeigen.Click
Dim connectionString As String = "server=localhost; database=notava; user id=****; password=****"
con.Open()
cmd.CommandText = "SELECT *, lehrer.name FROM klasse JOIN lehrer WHERE klasse.id_Klasse = " & id_Klasse & "AND WHERE klasse.id_tutor = lehrer.id_lehrer"
reader = cmd.ExecuteReader
lbl_KI_Klasseninfo.Text = "Klasse: " & cmb_KI_Jahrgang.SelectedItem & cmb_KI_Klasse.SelectedItem & vbCrLf &
vbCrLf & "Anzahl Schüler: " & reader("klasse.Anzahl_Schueler") & vbCrLf &
vbCrLf & "Tutor: " & reader("lehrer.name")
reader.Close()
con.Close()
End Sub
Error:
MySql.Data.MySqlClient.MySqlException: "Authentication to host '' for
user '' using method 'mysql_native_password' failed with message:
Access denied for user ''#'LAPTOP-D1CFSJ0F.speedport.ip' (using
password: NO)"
MySqlException: Access denied for user
''#'LAPTOP-D1CFSJ0F.speedport.ip' (using password: NO)
Keep your database object local so you can assure that they are closed and disposed. `Using...End Using blocks will do this for you even if there is an error.
Pass your connection string directly to the constructor of the connection.
Pass the sql statement and the connection directly to the constructor of the command.
As to your Select statement:
Don't use "*". You will get all the fields form both tables. It looks like you only need one field from each table. Don't retrieve unnecessary data.
A JOIN is done with an ON clause. If you did have more then one condition for the WHERE clause (not the case here) you would have a single WHERE and the additional conditions would be separated by AND.
You must call .Read on the reader to move to the first record. .Read advances the DataReader one record.
I used an Interpolated string for the label text. It saves all those ampersands and quotes also the Interpolated string assumes you want a string form the variables so you don't have to call .ToString explicitly. You can add hard returns by hitting Enter. VB adds the return for you again avoiding extra typing of ampersands and quotes.
Regarding the connection string. It looks like the database is on the same machine. My connection string looks like this server=localhost;user id=****;password=****;database=student where the **** would be replaced by your credentials. This URL has everything you ever wanted to know about connection strings. https://www.connectionstrings.com/mysql/
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim sql = "SELECT klasse.Anzahl_Schueler, lehrer.name FROM klasse JOIN lehrer ON klasse.id_tutor = lehrer.id_lehrer WHERE klasse.id_Klasse = #idKlasse"
Using con As New MySqlConnection("server=localhost; database=notava; user id=****; password=****")
Using cmd As New MySqlCommand(sql, con)
cmd.Parameters.Add("#idKlasse", MySqlDbType.Int32).Value = id_Klasse
con.Open()
Using reader = cmd.ExecuteReader
reader.Read()
lbl_KI_Klasseninfo.Text = $"Klasse: {cmb_KI_Jahrgang.SelectedItem} {cmb_KI_Klasse.SelectedItem}
Anzahl Schüler: {reader("klasse.Anzahl_Schueler")}
Tutor: {reader("lehrer.name")}"
End Using
End Using
End Using
End Sub

Error connecting to MySQL database (No such host is known)

While using the following code to connect to my SQL database:
MySqlConnection.ConnectionString = "server=vipervenom.net.mysql; userid=vipervenom_net_userinfo; password=PASSGOESHERE; database=vipervenom_net_userinfo;"
it prompts an error saying
Unable to connect to any of the specified MySQL hosts. ---> No such host is known.
I've been looking for hours to find an answer to this, but even though my host and login information is correct, it gives me that error. Take a look at the picture for login information -->
The entire source code:
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server=vipervenom.net.mysql; userid=vipervenom_net_userinfo; password=PASS GOES HERE; database=vipervenom_net_userinfo;"
Try
MySqlConnection.Open()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Dim MyAdapter As New MySqlDataAdapter
Dim sqlquery = "SELECT * From Users WHERE email='" & TextBox1.Text & "' AND password='" & TextBox2.Text & "';"
Dim command As New MySqlCommand
command.Connection = MySqlConnection
command.CommandText = sqlquery
MyAdapter.SelectCommand = command
Dim Mydata As MySqlDataReader
Mydata = command.ExecuteReader
If Mydata.HasRows = 0 Then
MsgBox("Wrong login information!")
Else
MsgBox("Login Successful! :D")
End If
Thank you in advance!
For what it's worth, vipervenom.net.mysql is not, and cannot be, a valid hostname, your hosting provider's statements to the contrary notwithstanding.
There aren't any hostnames ending in .mysql because that is not a valid top level domain name.
It's possible your hosting provider has an internal domain naming service handling .mysql as a TLD. But you won't be able to use that hostname from outside their network.
Ask your hosting provider what hostname to use for your MySQL server from outside their network.

String from Database set as public string

Ok from the answer from the previous question the reasoning still applies here but this time A different issue. There is a login system (Loginvb.vb) that I got for the launcher I was creating and was wondering 2 things:
Is there a better way to do the Login check with the database (as in
more secure) (the login style will have a web based registration
setting via PHP script)?
Is there a way to take a certain column (labled as access) in the database and put it
as a public string so I can check if it will equal 1 2 or 3 in a
different form labeled as Main.vb
Here is the current login check:
Public Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
If txtuserName.Text = "" Or txtpassWord.Text = "" Then
MsgBox("You cannot progress until you login....(moron =p)")
Else
'Connects To the Database
Dim connect As MySqlConnection
connect = New MySqlConnection()
connect.ConnectionString = "server=127.0.0.1;user id=sc;Password=derp;database=sclaunch" 'not the actual login ;)
Try
connect.Open()
Catch myerror As MySqlException
MsgBox("Error Connecting to Database. Please Try again !")
End Try
'SQL Query To Get The Details
Dim myAdapter As New MySqlDataAdapter
Dim sqlquerry = "Select * From login where username = '" + txtuserName.Text + "' And password= '" + txtpassWord.Text + "'"
Dim myCommand As New MySqlCommand()
'My fail attempt at what I am trying to do :(
Dim sql22 As MySqlConnection
sql22 = New MySqlConnection()
sql22.ConnectionString = "Select * From login where access ="
'End of fail attempt
myCommand.Connection = connect
myCommand.CommandText = sqlquerry
'Starting The Query
myAdapter.SelectCommand = myCommand
Dim mydata As MySqlDataReader
mydata = myCommand.ExecuteReader
'To check the Username and password and to validate the login
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
Else
'fail testing xD
Label3.Text = sql22
MsgBox("You are now Loged In!")
End If
End If
End Sub
Still basically learning more and more as I am coding all this got to love trial and error and the moments where you get stuck =/ (Sorry to the admins or whatever for fixing tag issues still new to the site xD)
Assuming that the same table login that contains the credentials contains also the access column that you want to retrieve, then I have changed a lot of your code
Dim sqlquerry = "Select * From login where username = #name AND password=#pwd"
Dim myCommand As New MySqlCommand(sqlquery, connect)
myCommand.Parameters.AddWithValue("#name", txtuserName.Text)
myCommand.Parameters.AddWithValue("#pwd", txtpassWord.Text)
Dim mydata = myCommand.ExecuteReader
If mydata.HasRows = False Then
MsgBox("Invalid Login")
Else
' the same record that contains the credentials contains the access field'
mydata.Read()
Label3.Text = mydata("access").ToString()
MsgBox("You are now Loged In!")
End If
What I have changed:
Removed the string concatenation and added the appropriate parameters
Removed myAdapter and every references to it (not needed, you don't
fill DataTable/DataSet)
Removed sql22 and every references to it. It's a Connection and you
try to use like a Command
Fixed the check on HasRows (Returns a boolean not an integer. Are you
using Option Strict Off?)

How to find out what database is linked to a certain ID in VB.NET

Basically, I have a VB.NET project with which I connect to a remote MySQL server.
The credentials that I can provide would be "server ip", "port", "database ID", "username" and "password".
Pretty basic stuff, except for the fact that it's the DB ID that's given and not the actual DB name. How can I retrieve the name of the database which is linked to that ID?
Currently I use this connection string to connect to it
connection.ConnectionString = "Host=" & server & ";port=" & port & ";user=" & uname & ";password=" & pword & ";"
Note: The reason I need to be able to have these in variables is because I plan to distribute this tool to some friends of mine, which have a different MySQL server to connect to, with different database names etc. And because not everyone needs to know what the database is called, due to safety reasons.
Edit: Another thing I could do is have my program check every database on the server and return which database has a certain table in it, then use that output for the rest of my program.
I've found a workaround, although this might not be applicable to other MySQL databases.
Here's how I did it:
Public Function sqlConnectTest(ByVal server, port, instance, uname, pword) As Boolean
Dim connection As MySqlConnection
connection = New MySqlConnection()
connection.ConnectionString = "Host=" & server & ";port=" & port & _
";user=" & uname & ";password=" & pword & ";"
Try
connection.Open()
MessageBox.Show("Connection Opened Successfully")
**Dim stm As String = "SELECT TABLE_SCHEMA from information_schema.TABLES where TABLE_NAME like 'survivor'"**
Dim cmd As MySqlCommand = New MySqlCommand(stm, connection)
Dim reader As MySqlDataReader = cmd.ExecuteReader()
While reader.Read()
DBname = reader.GetString(0)
End While
reader.Close()
connection.Close()
Return True
Catch mysql_error As MySqlException
MessageBox.Show("Error Connecting to Database: " & mysql_error.Message)
Return False
Finally
connection.Dispose()
End Try
End Function
Obviously this solution would only work when you have an information_schema database, containing a table which shows all the tables in all the databases on the server.