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

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

Related

HOW TO USE UPDATE IN SQL WITH VB

Can you please help me, what the problem of my code:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
'UPDATE Data
openCon()
Try
cmd.Connection = con
cmd.CommandText = "UPDATE emp_table SET FNAME = '" & TextBox1.Text & "', LNAME= '" & TextBox2.Text & "', AGE = '" & TextBox3.Text & "', GENDER ='" & Gender & "', OFFICE STAFF= '" & ComboBox1.Text & "' Where ID ='" & TxtID.Text & "' "
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Suceessfully Updated Record")
TxtID.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
RBMale.Checked = False
RBFemale.Checked = False
ComboBox1.Text = ""
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
There are many problems in your code and if you look around this site I think you will find many partial answers that step by step will help you solve your problems. So I try to give you an answer where all the problems are examined, discussed and solved.
First problem: How do you handle the connection.
It seems that you have a global connection instance called con that you open with openCon. This is not a good approach and always a source of problems. You always need to check if the connection is closed properly or not. For example, in the code above you have forgot to close the connection in case of exception and this will lead to other exceptions in some code not related to this one. You keep resources on the server locked to you and this will decrease the performance of every one connection to that server.
I would change your openCon to this
Public Function openCon() as MySqlConnection
Dim con as MySqlConnection = new MySqlConnection(....here connection string ...)
con.Open()
return con
End Function
This will create a new instance of the MySqlConnection every time you call this method Now you can remove the global connection instance and use the one returned by openCon in this way
Using con As MySqlConnection = openCon()
.... code that use the local con object
End Using
This will close and destroy the connection even if an exception occurs inside the Using block and the ADO.NET libraries are smart enough to use a thing called Connection Pooling to reduce the time required to build and open a connection with the same connection string.
Second problem: The syntax error.
Looking at the point of the error suggested by the message I can see a field name composed by two words separated by a space. This is fine, but then you should remember that the sql parser cannot understand this and you need to help it enclosing the two words in a backtick character (ALT+096) so the parser understand that this is a single field name. Given the fact column names are an internal information of no concern for your end user then why use spaces in column names? If possible remove the space in column names.
Third problem: Sql Injection and other syntax errors
You are concatenating strings to build an sql command. But this is an easy target for wannabe hackers. Suppose that I write in your textBox1 this string instead of a First Name: Mario'; --
Then your command becomes
UPDATE emp_table SET FNAME = 'Mario'; -- xxxxxxxxxxxx
everything after -- is considered a comment and the query is still executable, but it changes every record in emp_table to have a first name equal to Mario.
But the query could fail as well if someone writes a Last Name that contains an apostrophe like O'Leary just now the query is no more syntactically valid.
The solution to this is always one. Use Parameters.
Recap of changes to your code.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim cmdText as String = "UPDATE emp_table SET FNAME = #fname,
LNAME= #lname, AGE = #age, GENDER =#gender,
`OFFICE STAFF` = #staff
Where ID =#id"
Using con as MySqlConnection = openCon()
Using cmd as MySqlCommand = new MySqlCommand(cmdText, con)
Try
cmd.Parameters.Add("#fname", MySqlDbType.VarChar).Value = textBox1.Text
cmd.Parameters.Add("#lname", MySqlDbType.VarChar).Value = textBox2.Text
cmd.Parameters.Add("#age", MySqlDbType.VarChar).Value = textBox3.Text
cmd.Parameters.Add("#gender", MySqlDbType.VarChar).Value = gender
cmd.Parameters.Add("#staff", MySqlDbType.VarChar).Value = combobox1.Text
cmd.Parameters.Add("#id", MySqlDbType.VarChar).Value = txtID.Text
cmd.ExecuteNonQuery()
MsgBox("Suceessfully Updated Record")
TxtID.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
RBMale.Checked = False
RBFemale.Checked = False
ComboBox1.Text = ""
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
End Using
End Sub
In the recap I have added parameters for every single field that you want to update. But remember. Parameters should have a Type (The MySqlDbType here) that should match the type of the field and the value should be of the same type. For example it seems improbable that Age is a varchar field. So you should convert TextBox3.Text to an integer if the field is an integer.

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.

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.

MySQL Data NOT Deleting from table VB.NET

Why won't this delete the data in my MySQL database!?
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Try
dbCon = New MySqlConnection("Server=Localhost;Database=myusers;Uid=root;Pwd=Mypassword")
strQuery = "DELETE settings FROM settings WHERE user=" & Me.loginuser.Text
'* FROM settings WHERE user = "Testuser"'
SQLCmd = New MySqlCommand(strQuery, dbCon)
' OPEN THE DB AND KICKOFF THE QUERY
dbCon.Open()
DR = SQLCmd.ExecuteReader
While DR.Read
req1.Text = "" And exlink.Text = ""
End While
' DONE! Close DB
DR.Close()
dbCon.Close()
Catch ex As Exception
TextBox8.Text = ("Fail" & vbCrLf & vbCrLf & ex.Message)
End Try
Here is a picture of my database:
Alternatively I could somehow make it replace what is already in the database, in which case please help me with that.
Try
strQuery = "DELETE FROM settings " _
& " WHERE user = '" & Me.loginuser.Text & "'"
but as was stated earlier, you should be using parameterized queries. If you had a user named O'Brien then your query (as composed above) would fail because of the embedded single quote. When you use DELETE, you are deleting entire records and you already specify the table name in the FROM clause.
I will try to change your code in this way
Using con = New MySqlConnection("Server=.....")
con.Open()
Dim sqlText = "DELETE * FROM settings WHERE user = #ulogin"
Using cmd = new MySqlCommand(sqlText, con)
cmd.Parameters.AddWithValue("#ulogin", Me.loginuser.Text)
cmd.ExecuteNonQuery()
End Using
End Using
First and foremost, do not use string concatenation to create command texts to pass to the database engine. In that way you risk Sql Injections, also, if the user name contains a single quote (i.e. O'Hara) your code will fail with a syntax error (Same problems arise for date formatting, parsing numeric decimals and other globalization issues). Instead a parametrized query like the one in code above will avoid all of these problems.
In a parametrized query, the text of the query doesn't contains the actual value for the search condition or the update or insert data. Instead it contains placeholders ( in our case it is called #ulogin). The correct value to insert at the placeholders position is specified using one or more MySqlParameter added to the Parameters collection of the MySqlCommand. In this case I have used the AddWithValue method that derives the correct datatype directly from the datatype of the value. Because Me.loginuser.Text is a string value then the parameter will be treated as a string value replacing incorrect single quotes and removing extraneus characters usually used to Mount Sql Injections Attacks. The engine will do the rest inserting the correct value at the placeholder at execution time
EDIT: Seeing your comment about the MySql connector used, I will try to update my answer to show a semi-equivalent version for NET 1.
Try
Dim con As MySqlConnection = New MySqlConnection("Server=.....")
con.Open()
Dim sqlText as String = "DELETE * FROM settings WHERE user = #ulogin"
Dim cmd As MySqlCommand = new MySqlCommand(sqlText, con)
Dim par As MySqlParameter = New MySqlParameter("#ulogin", MySqlDbType.VarChar)
par.Value = Me.loginuser.Text
cmd.Parameters.Add(par)
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
I am not sure if the connector 1.0.10 supports the parameter name with the # prefix or just the : prefix
i dont think you can use double quotes in mysql, i think its single quotes only. try
Query = "DELETE * FROM settings WHERE user = '" & Me.loginuser.Text & "'"

vb.net application login using mysql database

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.