VB 'System.InvalidOperationException' occurred in MySql.Data.dll - mysql

I am trying to insert data into a table in MySql. Here is the code that I have.
Private Sub Submit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Submit.Click
Mysqlconn = New MySqlConnection()
Mysqlconn.ConnectionString = "server=localhost;userid=root;password=test;database=YHI"
Try
Mysqlconn.Open()
COMMAND = New MySqlCommand("INSERT INTO Main(Character,Import_Date) VALUES(#character, #import_date)")
COMMAND.Parameters.AddWithValue("#character", Character)
COMMAND.Parameters.AddWithValue("#import_date", ImportDate)
COMMAND.ExecuteNonQuery()
MessageBox.Show("Ore counts for " & Character.Text & " imported successfully")
Catch myerror As MySqlException
MessageBox.Show(myerror.Message)
Finally
Mysqlconn.Dispose()
End Try
Here is the error message I receive:
An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll
Additional information: Connection must be valid and open.
I'm new to programming in VB, so any help would be greatly appreciated.

You're not connecting your Mysqlconn to your COMMAND (at least I don't think so - can't see where you declare COMMAND).
There are a few ways to achieve this, but the simplest with your existing code would be just to set it as follows:
Mysqlconn.Open()
COMMAND = New MySqlCommand("INSERT INTO Main(Character,Import_Date) VALUES(#character, #import_date)")
COMMAND.Connection = Mysqlconn
COMMAND.Parameters.AddWithValue("#character", Character)

You are missing the connection.
COMMAND.Connection = MySqlconn

Related

Could not insert the data using vb.net into Mysql

I am trying to insert data into MySQL using VB.
When I use these textboxes to insert the data the data gets added, but I don't want to enter the text into textboxes but directly add the underlying information just by press of button (update). It is giving a syntax error to check MySQL version. It it a query error? I don't know how to do this. Please help. Here is my code.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Mysqlconn = New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=*****;database=data"
Dim reader As MySqlDataReader
Try
Mysqlconn.Open()
Dim query As String
query = "INSERT INTO 'data'.'etable'('eid','Name','Surname','Age')values('7','Andy','Roddick','35')"
command = New MySqlCommand(query, Mysqlconn)
reader = command.ExecuteReader
MessageBox.Show("Data Saved")
Mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Mysqlconn.Dispose()
End Try
End Sub
End Class
Try this, which fixes some other issues and potential issues as well:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim query As String = "INSERT INTO `data`.`etable`(eid,Name,Surname,Age)" & _
" VALUES (#eid, #Name, #Surname, #Age)"
Using con As New MySqlConnection("server=localhost;userid=DONT_USE_ROOT!;port=85;password=*****;database=data"), _
cmd As New MySqlCommand(query, con)
'Guessing at parameter types/lengths here.
cmd.Parameters.Add("#eid", MySqlDbType.Int32).Value = 7
cmd.Parameters.Add("#Name", MySqlDbType.VarChar, 20).Value = "Andy"
cmd.Parameters.Add("#Surname", MySqlDbType.VarChar, 25).Value = "Roddick"
cmd.Parameters.Add("#Age", MySqlDbType.Int32).Value = 35
conn.Open()
If cmd.ExecuteNonQuery() > 0 Then MessageBox.Show("Data Saved")
End Using
End Sub
Notice I also removed the exception handler. The Dispose() call in your old handler is now no longer needed (the Using block takes care of this), and I tend to advocate handling exceptions at a higher level than where they are thrown... though in this case you're already in the button event. What I really recommend here is moving the database code to it's own class, so this would all be in a separate method in that class. Then you could still have your exception handler here in the button click event, and the only thing in the Try block would be calling that method.
It's also very important to be in the habit of using query parameters for data that goes into sql queries, in order to prevent sql injection attacks. What you had wasn't vulnerable to attack yet, but it didn't lend any confidence that it wouldn't be vulnerable soon.
The correct character to enclose table name and field names is the backtick not the single quote. Use ALT+096 on your numeric keypad to insert it.
query = "INSERT INTO `data`.`etable`(`eid`,`Name`,`Surname`,`Age`) " & _
"values('7','Andy','Roddick','35')"
Said that, check if you database table has the field eid and Age of type varchar. If the fields are numeric (as the name seems to imply) then your query should be changed to
query = "INSERT INTO `data`.`etable`(`eid`,`Name`,`Surname`,`Age`) " & _
"values(7,'Andy','Roddick',35)"
You code also contains some bad practice that need to be removed to avoid future problems
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim query As String
query = "INSERT INTO `data`.`etable`(`eid`,`Name`,`Surname`,`Age`) " & _
"values(7,'Andy','Roddick',35)"
Using Mysqlconn = New MySqlConnection
Using command = New MySqlCommand(query, Mysqlconn)
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=*****;database=data"
Try
Mysqlconn.Open()
Dim rowsAffected = command.ExecuteNonQuery()
if rowsAffected > 0 Then
MessageBox.Show("Data Saved")
End If
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
First enclose all disposable objects in a Using statement to be sure that they are closed and disposed also in case of exceptions then do not use ExecuteReader for INSERT, UPDATE and DELETE queries, instead the correct method to use is ExecuteNonQuery

Error connecting to SQL with VB

So i tried to connect my sql database to my vb project but it gives me this error:
Error Connecting to Database : Authentication to host "for user" using
method 'mysql_native_password' failed with message : Acces denied for
user "#'N56VB' (using password : NO)
N56VB is my pc
UPDATE the error wich I get now is : A first chance exception of type
'System.ArgumentException' occurred in System.Data.dll
Additional information: Keyword not supported.
If there is a handler for this exception, the program may be safely
continued
I dont know what to do anymore it will be a stupid I guess ,be easy on me i'm a noob :(
I hope someone knows the problem
Imports MySql.Data.MySqlClient
Imports System.Data.Sql
Imports System
Imports System.Data
Public Class NieuweItems
Public dbconn As New MySqlConnection("Data Source=localhost;user id=root;password=;database=gip;")
Dim conn As New MySqlConnection
Private Sub btn_return_Click(sender As Object, e As EventArgs) Handles btn_return.Click
Me.Close()
SalesApplication.Show()
End Sub
Private Sub btn_inlezen_Click(sender As Object, e As EventArgs) Handles btn_inlezen.Click
Dim sqlCommand As New MySqlCommand
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim strStockSQL As String
SQLConnection.ConnectionString = "Data Source= localhost ;user id = root'#'localhost; password = ;database=gip;table=stock;"
Try
conn.Open()
strStockSQL = "INSERT INTO Barcode " & txtBarcode.Text & "INSERT INTO Naam_Product" & txtNaam.Text & "INSERT INTO Verkoopprijs" & txtVP.Text
sqlCommand.ExecuteNonQuery()
SQLConnection.Close()
conn.Close()
Catch myerror As MySqlException
MessageBox.Show("Error Connecting to Database: " & myerror.Message)
Finally
conn.Close()
End Try
End Sub
End Class
I presume that the error is occurring inside the "btn_inlezen_Click" event handler? I think what's happening is that you're declaring a new empty MySqlConnection, opening the connection inside your Try block and only then are you setting the ConnectionString. Because MySqlConnection was declared with no parameters it might be trying to use N56VB as the user account and this doesn't have any permissions on your MySQL db.
So set your connection string before opening the connection.

Fatal Error Encounter During Command Execution MySQL VB

ijust finish my code for inserting data using the vb and mySQL but when i run my webpage it seem have an error Fatal Error Encounter During Command Execution . Please help some how to solve it. below is my code.
Imports System.Data.SqlClient
Imports MySql.Data.MySqlClient
Partial Class Request
Inherits System.Web.UI.Page
Dim MessageBox As Object
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
txt1.Focus()
txt2.Focus()
txt3.Focus()
txt4.Focus()
txt5.Focus()
txt6.Focus()
txt7.Focus()
ddl1.Focus()
ddl2.Focus()
ddl3.Focus()
ddl4.Focus()
End Sub
Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
'Create sql connection and fetch data from database based on employee id
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String = ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Try
conn.ConnectionString = strConnectionString
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
End Try
' Dim cr_id As String
' cr_id = "CR004"
Dim iReturn As Boolean
Using SQLConnection As New MySqlConnection(strConnectionString)
Using sqlCommand As New MySqlCommand()
sqlCommand.Connection = SQLConnection
With sqlCommand
.CommandText = "INSERT INTO cr_record(idcr_record,Emplid,Nama,date,DeptDesc,email,change,reasonchange,problem,priority,reasondescription,systemrequest) VALUES (#IDCR,#Emplid,#Nama,#date,#DeptDesc,'#email,#change,#reasonchange,#problem,#priority,#reasondescription,#systemrequest)"
' .CommandTimeout = 5000000
.CommandType = Data.CommandType.Text
.Parameters.AddWithValue("#Emplid", txt1.Text)
.Parameters.AddWithValue("#Nama", TextBox1.Text)
.Parameters.AddWithValue("#date", txt5.Text)
.Parameters.AddWithValue("#DeptDesc", txt2.Text)
.Parameters.AddWithValue("#email", txt4.Text)
.Parameters.AddWithValue("#change", ddl2.Text)
.Parameters.AddWithValue("#reasonchange", txt6.Text)
.Parameters.AddWithValue("#problem", ddl3.Text)
.Parameters.AddWithValue("#priority", rbl1.Text)
.Parameters.AddWithValue("#reasondescription", txt7.Text)
.Parameters.AddWithValue("#systemrequest", ddl4.Text)
End With
Try
SQLConnection.Open()
' sqlCommand.ExecuteNonQuery()
sqlCommand.ExecuteNonQuery()
iReturn = True
MsgBox("Added Successfully")
Catch ex As MySqlException
MsgBox(ex.Message.ToString & Err.Description)
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
Return
End Sub
End Class
you probably forgot to add this parameter #IDCR
.Parameters.AddWithValue("#IDCR", toyourvariable)
Syntax error in your query:
[...snip...]tDesc,'#email,#change,#rea[...snip...]
^---mis-placed quote.
Reserved words:
[...snip...]c,email,change,reasonc[...snip...]
^^^^^^---- quote with backticks: `change`
Solution that i used and it really works.
This error is mostly caused by a MISSING or Incorrectly Spelled Parameter declaration. eg. #FirstName mistakenly spelled for #FirtName.
Make sure that all the parameters that are declared in the sql query are all declared in the AddwithValue Parameter declaration. (It helps to count the query versus the Addwithvalues).
The best solution is for visual studio to provide information about the missing Parameter. Use a Try-Catch block. In the catch block use Messagebox.show(ex.Innerexception.Message) instead of Messagebox.show(ex.message). This will show the exact Parameter that is missing. eg. below
Try
conCommand.Parameters.Addwithvalue("#FirstName", txtFirstName.text)
conCommand.Parameters.Addwithvalue("#MiddleName", txtMiddleName.text)
conCommand.Parameters.Addwithvalue("#LastName", txtLastName.text)
conCommand.Parameters.Addwithvalue("#PhoneNo", txtPhoneno.text)
catch ex as exception
Messagebox.show(ex.innerexception.Message)
End Try
Hope this helps. Its really great that we share our ideas in the world of programming.

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/

Host x is not allowed to connect to this mysql server

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