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/
Related
I am connecting a chart object in mysql database but getting this error:
object reference not set to an instance of an object
This is the code I used:
Imports MySql.Data.MySqlClient
Public Class Form1
Dim con As New MySqlConnection
Dim com As MySqlCommand
Dim dt As New DataTable
Private Sub btnlaod_Click(sender As Object, e As EventArgs) Handles btnlaod.Click
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=;database=noh_mis"
Dim Reader As MySqlDataReader
Try
con.Open()
Dim query As String
query = "Select * From database.students_profile"
Reader = com.ExecuteReader
While Reader.Read
Chart1.Series("Male").Points.AddXY(Reader.GetString("Gender"), Reader.GetString("GradeLevel"))
End While
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
End Class
You do not make a command before using com.ExecuteReader. You make a string of sql, but never connect that with your database.
Try adding the below line after building query but before Reader = com.ExecuteReader:
com = New MySqlCommand(query, con)
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
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.
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
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)