Host x is not allowed to connect to this mysql server - mysql

I am trying to make a simple registration & activation system using my mysql server and vb.net and I am using the code below:
Imports MySql.Data.MySqlClient
Public Class ActivateMe
Dim MysqlConn As MySqlConnection
Dim myAdapter As New MySqlDataAdapter
Dim myData As MySqlDataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection()
Try
MysqlConn.Open()
Dim checkUsername As String = "SELECT COUNT(*) FROM users WHERE verif=#p1 and username=#p2"
Dim insertData As String = "INSERT INTO users(hasVerif) VALUES(#p3)"
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
myCommand.Parameters.AddWithValue("#p1", TextBox1.Text)
myCommand.Parameters.AddWithValue("#p2", currentRegUser)
Dim result = myCommand.ExecuteScalar()
If result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
Using myCommand2 = New MySqlCommand(insertData, MysqlConn)
myCommand.Parameters.AddWithValue("#p3", 1)
myCommand2.ExecuteNonQuery()
MsgBox("Successfully Activated! You May Now Login!", MsgBoxStyle.Information, "Success")
Me.Close()
End Using
Else
MsgBox("Invalid Activation Code", MsgBoxStyle.Critical, "Error")
End If
End Using
End Using
MysqlConn.Close()
Catch myerror As MySqlException
MessageBox.Show("Cannot connect to database: " & vbNewLine & vbNewLine & myerror.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
End Class
The program sends the activation code to the email successfully and uploads the activation code to the database for checking but when I am on the activation form and enter the code, it says:
Host (my pc name) is not allowed to connect to this mysql server
In the different forms, the server accepts the connection and allows access to the database so I don't see why it would be different here...
Please send me help!
Thanks
rodit

I'm not very familiar with MySQL under .NET but I believe you do something a bit odd here. First you open a connection without a connection string (I assume that uses default parameters)
MysqlConn = New MySqlConnection()
Try
MysqlConn.Open()
and then you open another connection using an explicit string
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
Notice it's the same MysqlConn variable (with different objects).
So the MySqlException you're catching could be coming from any one of them. You can use that exception to find out which of the open calls actually triggered the exception (I assume it's first one).
You should probably also cleanup code and keep only one open call.
Andrei

Related

MySql - An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll

I am using MYSQL database for that...I get this following Error...Please anyone can help me?
Imports System.Data
Imports MySql.Data Imports MySql.Data.MySqlClient
Public Class formLogin
Dim connStr As String = "server=localhost;user=root;database=ssknet;port=3306;password=;"
Dim connection As New MySqlConnection(connStr)
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
connection.Open()
Dim cmd As New MySqlCommand("SELECT * FROM user WHERE username=#username and password=#password", connection)
cmd.Parameters.Add("#username", MySqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#password", MySqlDbType.VarChar).Value = txtPassword.Text
Dim adapter As New MySqlDataAdapter
Dim table As New DataTable
adapter.Fill(table)
If table.Rows.Count <= 0 Then
MessageBox.Show("Invalid Username or Password")
Else
MessageBox.Show("Login Success!")
End If
'cmd.ExecuteNonQuery()
connection.Close()
End Sub
End Class
I want to access database right now. Quick frnds
You are missing a critical step. You are not assigning any command to your adapter. It doesn't know how to query anything without a command
Dim adapter As New MySqlDataAdapter(cmd)
Next, according to the MySql Reserved KeyWords, user and password are reserved and to use them in a query as field names you should put backticks (ALT+096) around them. So the query should be written as
Dim cmd As New MySqlCommand("SELECT * FROM `user`
WHERE username=#username
AND `password`=#password", connection)
A part from this your code is good enough albeit there are a couple of thing to consider.
First, connection object should not be kept as global objects. This leads to many problems with the resources kept on the server and with closing/opening the connection when there is an error. Just create and discard the connection inside a using statement
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Using connection = New MySqlConnection(connStr)
connection.Open()
.... all of your code except the close connection
End Using ' this close the connection also in case of exceptions
Second, you don't need an SqlDataAdapter and a datatable if you just want to check if the user/password exists
Dim reader = cmd.ExecuteReader()
if reader.HasRows then
MessageBox.Show("Login Success!")
Else
MessageBox.Show("Invalid Username or Password")
End If
Third, it is a great security risk to keep password in plain text inside your database and then using queries to retrieve it. You should use Salt and Hashing methods to store and retrieve password

Trying to enter records into a mysql database using vb.net but its not working and I cant figure out why

Mysql is connected to my vb so thats not the problem Im not really sure whats wrong.
This is a register account form, im using xampp for mysql.
Public Class Reigsteraccount
Public Class Form1
Dim conn As MySqlConnection
Dim COMMAND As MySqlCommand
Dim WithEvents Button1 As New Button
Dim WithEvents Textbox1 As New TextBox
Dim WithEvents Textbox2 As New TextBox
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString = "server=localhost;userid=root;password=root;database=compproject"
Dim READER As MySqlDataReader
Try
conn.Open()
Dim Query As String
Query = "insert into compproject.users (Usernames,Passwordhash) values ('" & Textbox1.Text & "','" & Textbox2.Text & "')"
COMMAND = New MySqlCommand(Query, conn)
READER = COMMAND.ExecuteReader
MessageBox.Show("Record added")
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
End Class
First of all, that's some very bad code - I know this isn't CodeReview, but still, it needs to be pointed out! Have a look at codereview.stackexchange.com if you want to brush up on best practices (I appreciate you might be a first time coder...).
To answer the question, you are using COMMAND.ExecuteReader - this should be replaced with COMMAND.ExecuteNonQuery. You're not reading from the database, you're writing data into it (INSERT command in the SQL).
If it still doesn't work after changing that, please update your question to include more detail, such as the exception generated, etc.

VB.NET application unable to run on other computer

I can debug my project with no errors, but when I build it and copy the executable application to another computer, the application is not running at all. The form does not even appear on screen.
(Here) is the screenshot of my error.
Here is my source code.
Imports System.Data.SqlClient
Imports MySql.Data.MySqlClient
Public Class Form1
Dim MySQLConnection = New MySqlConnection
Dim Command As New MySqlCommand
Dim MyAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim str_carSql As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim response As Boolean = False
Button1.Enabled = False
Try
response = My.Computer.Network.Ping("www.db4free.net")
Label2.Text = "ONLINE"
Label2.ForeColor = Color.Green
Button1.Enabled = True
Catch ex As Exception
Label2.Text = "OFFLINE"
Label2.ForeColor = Color.Red
MsgBox("No internet connection!", MsgBoxStyle.Critical)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Cursor = Cursors.WaitCursor
Try
MySQLConnection.ConnectionString = "server=db4free.net ;port=3306; user=prav5ef; password=prav5eF; database=databasetest;"
MySQLConnection.Open()
MsgBox("Connected to server!")
Catch ex As Exception
MsgBox("Failed connecting to server!", MsgBoxStyle.Critical)
End Try
Try
str_carSql = "insert into databasetest (id,name,password) values (#id,#name,#password)"
sqlCommand.Connection = MySQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.Parameters.AddWithValue("#id", TextBox1.Text)
sqlCommand.Parameters.AddWithValue("#name", TextBox2.Text)
sqlCommand.Parameters.AddWithValue("#password", TextBox3.Text)
sqlCommand.ExecuteNonQuery()
Catch ex As Exception
MsgBox("ID existed: Could not insert record")
End Try
MsgBox("Done")
Application.Restart()
End Sub
End Class
Here is how the application suppose to show :
And the online database that I am using is db4free.net :
Since you did not provide enough information on the error, these are the following problems you might be experiencing, and the solutions to said problems:
A.) Your client may not be running the correct .NET framework for your Program. In which case, install the correct .NET Framework by downloading it here.
B.) You did not include the mysl.data.dll on the client unit. In which case, download the .dll from here and install it in the client unit.

PC denied acces to connect to Database

Hi im relatively new to VB.NET so please bear with me here.
Im trying to setup a DB connection to my localhost everything looks good in my code except I get the error, when running the program, this PC is not allowed to connect to this DB, as you can see in the following image:
Here is my code I use to connect to the DB
Imports MySql.Data.MySqlClient
Public Class sreg
Dim ServerString As String = "Server=localhost;User Id=root;Password="";Database=vbdb"
Dim SqlConnection As MySqlConnection = New MySqlConnection
Private Sub sreg_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim SqlConnection As MySqlConnection = New MySqlConnection
SqlConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MsgBox("Successfully connected to MySQL DB")
Else
SQLConnection.Close()
MsgBox("Connection is Closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveNames(ByRef SQLStatment As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatment
.CommandType = CommandType.Text
.Connection = SqlConnection
.ExecuteNonQuery()
End With
SqlConnection.Close()
MsgBox("Succesfully Added!")
SqLConnection.dispose()
End Sub
End Class
I suspect the problem might be in this line SqlConnection.ConnectionString = ServerString since above line returns error when I run the program, however when I remove it I get it to work, but get the not allowed to connect to DB error, as you can see in the image
It looks like you are trying to connect to a MySQL server and it looks like the connection string you need is slightly different than for a MSSQL server:
"Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
Source: https://www.connectionstrings.com/mysql/

SQL and VISUAL BASIC 2008 Queries

How can I write a sql query that takes information from a database, and then put in the text in a label? I'm not really sure how to do this.
MSDN has lots of examples of getting data via ADO.NET. E.g. http://msdn.microsoft.com/library/dw70f090.
You will need to adjust the connection and command types (and the connection string) to be correct for My SQL. If you have ODBC drivers for My SQL then you can follow the ODBC example with just a change of connection string.
For using MySQL with .NET I'd recommend you this tutorial, and for your problem specially part 6, about reading the data with a MySQLDataReader.
An (almost working) sample by copy&paste from there with some changes:
Private Sub getData()
Dim conn As New MySqlConnection
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
Dim SQL As String
SQL = "SELECT LabelContent FROM myTable"
conn.ConnectionString = myConnString ' your connection string here'
Try
conn.Open()
Try
myCommand.Connection = conn
myCommand.CommandText = SQL
myReader = myCommand.ExecuteReader
' loop through all records'
While myReader.Read
Dim myLabelValue as String
myLabelValue = myReader.GetString(myReader.GetOrdinal("LabelContent"))
' ... do something with the value, e.g. assign to label '
End While
Catch myerror As MySqlException
MsgBox("There was an error reading from the database: " & myerror.Message)
End Try
Catch myerror As MySqlException
MessageBox.Show("Error connecting to the database: " & myerror.Message)
Finally
If conn.State <> ConnectionState.Closed Then conn.Close()
End Try
End Sub
For selecting one column to label from ms access 2007 database just follow this step
Create ms access database for example i make name "test.accdb" and make 1 column for example column name is "ColumnName" and one table with name "Table1"
save it on whatever folder
open vb 2008 and make one form
import adodb on first writing
write this code inside class
Sub lihat()
Dim str As String = "select * from Table1"
Dim cn As New OleDb.OleDbConnection
Dim com As New OleDb.OleDbCommand
Dim adp As OleDb.OleDbDataReader
With cn
.ConnectionString = "Provider=Microsoft.ace.oledb.12.0;data source=test.accdb;persist security info=false"
.Open()
End With
With com
.Connection = cn
.CommandText = str
End With
adp = com.ExecuteReader
adp.Read()
Label1.Text = adp(1)
cn.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lihat()
End Sub
number 1 on adp(1) is number of column on Table1.