'System.Security.Authentication.AuthenticationException' occurred in MySql.Data.dll - mysql

I tried to use this code to login to my vb.net application using mysql. But I have this error
An unhandled exception of type 'System.Security.Authentication.AuthenticationException' occurred in MySql.Data.dll. Additional information: Échec d'un appel à SSPI, consultez l'exception interne. I have this error only with windows 10, there are no problems with Windows 7
I read here a solution.
I tried to add this line
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;" before
Dim Str As String = "SERVER=localhost;
uid =root;
DATABASE =mag;
PASSWORD =;""
but it didn't work.
Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Str As String = "SERVER=localhost; uid =root;DATABASE =mag;PASSWORD =;"
Dim cc As New MySqlConnection(Str)
Try
conn.Open()
Dim Sql = "SELECT * FROM tab1 WHERE login='" & TextBox1.Text & "' and password='" & TextBox2.Text & " '"
Dim cmd = New MySqlCommand(Sql, cc)
Dim dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows = 0 Then
MsgBox("Error.", vbQuestion)
Else
Me.Hide()
Form2.Show()
End If
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

Related

Remote database connection in VB.net not working

I'm currently working on a MySQL connection in my VB.net app. I have a form which has the following code:
Imports System.Data
Imports System.Data.SqlClient
Public Class Form4
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ConnectToSQL()
End Sub
Private Sub ConnectToSQL()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Password As String
Dim Password2 As String
Dim userName As String
Try
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT user_username, user_pass FROM users WHERE (user_username = '" & txtUsername.Text & "' ) AND (user_pass = '" & txtPassword.Text & "')"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
If lrd.HasRows Then
While lrd.Read()
Password = lrd("Password").ToString()
userName = lrd("UserName").ToString()
Password2 = txtPassword.Text()
If Password = Password2 And userName = txtUsername.Text Then
MessageBox.Show("Logged in successfully as " & userName, "", MessageBoxButtons.OK, MessageBoxIcon.Information
)
Form2.Show()
Me.Hide()
txtPassword.Text = ""
txtUsername.Text = ""
End If
End While
Else
MessageBox.Show("Username or Password incorrect...", "Authentication Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
txtPassword.Text = ""
txtUsername.Text = ""
End If
End If
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
Everytime I run the application, I enter the login details correctly and click on the sign in button (Button2). The problem is, it doesn't do anything. It doesn't throw an exception, doesn't even try to login to the server as far as I can tell. I replaced the login details with that of my own server, so that's not the problem. Did I miss something?
Don't store passwords in clear-text!
Furthermore your code is prone to sql incjection.
Nothing happens because this If will never be true:
...
If con.ConnectionString = "Network Library=DBMSSOCN;""Data Source=myserver,1433;""Initial Catalog=users;""User ID=myuser;password=mypass;" Then
...

InvalidOperationException ocurred

I am trying to access MySql database but get this error:
Exception thrown: 'System.InvalidOperationException' in MySql.Data.dll
Additional information: The CommandText property has not been properly initialized.
This Would be my Code
Imports MySql.Data.MySqlClient
Public Class Login
Dim cn As New MySqlConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cn.ConnectionString = "server=localhost; userid=root; password=root; database=pos"
cn.Open()
MsgBox("Connected")
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
cn.Close()
Dim myadapter As New MySqlDataAdapter
Dim sqlquery = "SELECT * from pos.values where username='" & txtUsername.Text & "' AND password='" & txtPassword.Text & "'"
Dim mycommand As New MySqlCommand
mycommand.Connection = cn
cn.Open()
myadapter.SelectCommand = mycommand
Dim mydata As MySqlDataReader
mydata = mycommand.ExecuteReader
If mydata.HasRows = 0 Then
Beep()
MsgBox(txtUsername.Text & " Invalid")
Else
MsgBox("Welcome " & txtUsername.Text)
MainWindow.Show()
Me.Hide()
cn.Close()
End If
End Sub
End Class
Just like the error says, you never set the CommandText property of the MySqlCommand object. You've defined a SELECT query, but never use it anywhere. Set it on the command object before trying to use that object:
mycommand.CommandText = sqlquery
Note: Be aware that your code is wide open to SQL injection attacks. You should use query parameters instead of directly executing user input as code. Basically, you're allowing users to execute any code they want on your database.
Also: You are storing user passwords in plain text. This is grossly irresponsible to your users. If you can read their password, so can an attacker. User passwords should be obscured with a 1-way hash so that they can never be read, not even by you as the system owner.

Can't display results of mysql query

I'm new to Visual Basic, I am quite proficient in php which is why I moved on to VB. I am having trouble getting data and displaying it. Here's my full code which is supposed to look in my database "game", find the row with username "kenazz" and display the username "kenazz".
Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cs As String = "Database=game;Data Source=localhost;" _
& "User Id=root;Password="
Dim conn As New MySqlConnection(cs)
Try
conn.Open()
Dim stm As String = "SELECT * FROM users WHERE users.username = 'Kenazz'"
Dim cmd As MySqlCommand = New MySqlCommand(stm, conn)
Dim reader As MySqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(reader.GetInt32("id") & ": " _
& reader.GetString("username"))
End While
reader.Close()
Catch ex As MySqlException
Console.WriteLine("Error: " & ex.ToString())
Finally
conn.Close()
End Try
End Sub
End Class
Where am I going wrong?

VB2013 & MySQL not talking properly and program freezing

I have been working on a small project for a while now - it takes a plain text input from an Ardiuno Board (simple text, only a few characters). It's a simple NFC Card tagging program. The program is supposed to take the input from the SerialPort and check the input text against a MySQL database. If it finds the name in the database, then it is to update one column, that's it.
The problem is two fold - first, while I can query the database and get a list of people within the database, the tagging side of the program will not update the database, not matter what input is passed to it. Second - whenever the program receives any input, the program locks up and the GUI becomes unresponsive.
My code is below, and I am happy for any Questions, Comments, or Criticisms. Yes, the MySQL server is on port '8228'. This code is driving me mad, and I apologize as it may seem messy...
Imports System.IO.Ports
Imports System.Threading
Imports System.Text
Imports System.Data.Odbc
Public Class Form1
Dim WithEvents SerialPort As New IO.Ports.SerialPort
Dim ListStr As String
Dim SQLString As String
Dim fstoday As String = Today.Day.ToString + "_" + Today.Month.ToString + "_" + Today.Year.ToString
Dim NextLine As String
Dim PortNum As String
Dim SqlConn As String
Dim sw As StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs)
Timer1.Start()
SerialPort.ReceivedBytesThreshold = 4
PortNum = "COM6"
SqlConn = "mydomain.local"
Call TestSQLConnectionToolStripMenuItem_Click()
Call ConnectSerial()
'create todays log file
Dim filesys As New FileStream("c:\TagLog\Log-" + fstoday + ".txt", FileMode.Append, FileAccess.Write, FileShare.Write)
filesys.Close()
End Sub
Private Sub ConnectSerial()
'set the USB (COM) Port and Bandwidth (BaudRate)
Try
SerialPort.BaudRate = 115200
SerialPort.PortName = PortNum
SerialPort.Open()
LabPort.Text = "Reader OK"
LabPort.ForeColor = Color.Green
Catch
SerialPort.Close()
LabPort.Text = "Reader Not Found"
LabPort.ForeColor = Color.Red
End Try
End Sub
'This handles setting and reading from the serial port
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Dim str As String = SerialPort.ReadExisting()
Invoke(myD1, str)
End Sub
'This makes the serial input into String format
Delegate Sub myMethodDelegate(ByVal [text] As String)
Dim myD1 As New myMethodDelegate(AddressOf myShowStringMethod)
Sub myShowStringMethod(ByVal myString As String)
ListStr = ""
SQLString = ""
'display text to our textbox
TextBox2.AppendText(myString)
'Add the last input to the listbox
ListBox1.Items.Add(TextBox2.Text)
ListStr = ListBox1.Items(ListBox1.Items.Count - 1)
SQLString = "Select * From TagTable where QuickName='" + myString + "';"
Try
Dim cn As OdbcConnection = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Dim cmd As New OdbcCommand(SQLString, cn)
SQLString = "UPDATE tagtable SET State = NOT State, Time=Now() WHERE QuickName='" + myString + "';"
sw.WriteLine(vbCr + Now() + " " + myString)
Call UpdateSQL()
cn.Close()
Catch ex As Exception
sw.WriteLine(vbCr + Now() + ex.ToString)
End Try
sw.Close()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'Once per Tick, check what the COM port is saying.
If SerialPort.IsOpen Then
TextBox2.Text = ""
Else
TextBox2.Text = ""
Call ConnectSerial()
End If
End Sub
Private Function IIf(fileExists As Boolean, p2 As String) As Object
Throw New NotImplementedException
End Function
Private Sub UpdateSQL()
Dim cn As OdbcConnection = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
'check connection to the SQL Server and update the records
Dim cmd As OdbcCommand = New OdbcCommand(SQLString, cn)
cn.Open()
LabSQL.ForeColor = Color.Green
LabSQL.Text = "SQL OK"
If SQLString <> "" Then
Try
cmd.ExecuteNonQuery()
cn.Close()
LabSQL.ForeColor = Color.Green
Catch ex As Exception
LabSQL.ForeColor = Color.Red
LabSQL.Text = "SQL Not OK"
sw.WriteLine(vbCr + Now() + " " + ex.ToString)
cn.Close()
End Try
Else
cn.Open()
LabSQL.ForeColor = Color.Green
End If
'If there is a problem, change Sql Label, and clsoe the error'd connection.
cn.Close()
SQLString = ""
End Sub
Private Sub TestSQLConnectionToolStripMenuItem_Click() Handles TestSQLConnectionToolStripMenuItem.Click
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
'check connection to the SQL Server
Try
cn.Open()
LabSQL.ForeColor = Color.Green
LabSQL.Text = "SQL OK"
cn.Close()
'If there is a problem, change Sql Label, display the error in a message box and Close the error'd connection.
Catch ex As OdbcException
LabSQL.ForeColor = Color.Red
LabSQL.Text = "SQL Not OK"
cn.Close()
End Try
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Dim msgans As String
msgans = MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo, "Exit?")
If msgans = vbYes Then
SerialPort.Close()
Me.Close()
End If
End Sub
Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click
PortNum = "COM1"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
PortNum = "COM2"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem5_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem5.Click
PortNum = "COM3"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem6_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem6.Click
PortNum = "COM4"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem7_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem7.Click
PortNum = "COM5"
Call ConnectSerial()
End Sub
Private Sub ToolStripMenuItem8_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem8.Click
PortNum = "COM6"
Call ConnectSerial()
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
MsgBox("Made by Phill C at Epoq IT. Tag Control V2.3")
End Sub
Private Sub LocalMachineToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LocalMachineToolStripMenuItem.Click
SqlConn = "localhost"
Call TestSQLConnectionToolStripMenuItem_Click()
End Sub
Private Sub OtherLocationToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OtherLocationToolStripMenuItem.Click
SqlConn = InputBox("Enter the SQL Address or Location.", "SQL Location Input", "localhost").ToString
Call TestSQLConnectionToolStripMenuItem_Click()
End Sub
Private Sub ShowUserListToolStripMenuItem_Click() Handles ShowUserListToolStripMenuItem.Click
Dim cn As OdbcConnection
Dim Outstring As String = ""
SQLString = "Select Person,Quickname from TagTable"
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Dim cmd As New OdbcCommand(SQLString, cn)
Dim Query = cmd.ExecuteReader()
Outstring = "FULL NAME, QUICK NAME" + vbCr
While Query.Read
Outstring = Outstring + Query.Item(0) + " , " + Query.Item(1) + vbCr
End While
MsgBox(Outstring)
Query.Close()
cn.Close()
End Sub
Private Sub AddUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddUserToolStripMenuItem.Click
Dim QueryFull = InputBox("Enter the New Users Full Name.", "New User Input", "New User").ToString
Dim QueryQName = InputBox("Enter the New Users Quick Name / Nickname.", "New User Input", "New User").ToString
SQLString = "Insert Into TagTable (QuickName,Person,State,Time) Values ('" + QueryQName + "','" + QueryFull + "','In', NOW());"
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Try
Dim cmd As New OdbcCommand(SQLString, cn)
MsgBox("New User has been setup on the Server.")
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox("New User setup has failed, please contact IT Support")
End Try
End Sub
Private Sub DeleteUserToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteUserToolStripMenuItem.Click
Dim QueryFull = InputBox("Enter the Users Full Name.", "Delete User Input", "User To be deleted").ToString
Dim QueryQName = InputBox("Enter the Users Quick Name / Nickname.", "Delete User Input", "User To be deleted").ToString
SQLString = "Delete From TagTable Where QuickName='" + QueryQName + "' AND Person='" + QueryFull + "';"
Dim cn As OdbcConnection
cn = New OdbcConnection("driver={MySQL ODBC 5.3 Unicode Driver};server=" + SqlConn + ";port=8228;database=tagging;uid=TagUser;pwd=tagging;")
cn.Open()
Try
Dim cmd As New OdbcCommand(SQLString, cn)
MsgBox("User has been removed from the Server.")
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox("User revomal has failed, please check the full name and quick names, and try again.")
End Try
End Sub
End Class

delete and update command not working.....program in asp.net2010, SQLYOG DATABASE 5.0

in ths program my DISPLAY and ADD button is working but at the time of UPDATE and DELETE record it gives the exception error i.e CHECK THE MANUAL THAT CORRESPONDS TO YOUR MYSQL SERVER FOR THE RIGHT SYNTAX.....
can you please correct my syntax...?
Imports MySql.Data.MySqlClient
Imports System.Data
Partial Class _Default Inherits System.Web.UI.Page
Dim connection As MySqlConnection = New MySqlConnection("data source=localhost;database=dbconnect;user id=root;password=search;")
Dim mydataset As New DataSet()
Dim mydataadpter As MySqlDataAdapter = New MySqlDataAdapter()
Public query As String
' Dim con As MySqlConnection = New MySqlConnection("data source=localhost;database=dbconnect;user id=root;password=search;")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
connection.Open()
End Sub
Protected Sub btn_display_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_display.Click
Dim mysql As MySqlCommand = New MySqlCommand("select * from userinfo", connection)
mydataadpter.SelectCommand = mysql
mydataadpter.Fill(mydataset, "product")
Try
GridView1.DataSource = mydataset
GridView1.DataBind()
GridView1.DataMember = "product"
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_add.Click
query = "INSERT INTO userinfo VALUES("
query = query + txt_userid.Text + ",'" + txt_username.Text + "'," + txt_age.Text + ")"
Dim MySqlCommand = New MySqlCommand(query, connection)
Dim i As Integer = MySqlCommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is saved")
Else
MsgBox("record is not saved")
End If
End Sub
Protected Sub btn_update_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_update.Click
Try
query = "UPDATE USERINFO SET username='" + txt_username.Text + "',"
query = query + "age=" + txt_age.Text
query = query + "WHERE userid=" + txt_userid.Text
Dim mysqlcommand = New MySqlCommand(query, connection)
MsgBox(query)
Dim i As Integer = mysqlcommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is updated")
Else
MsgBox("record is not updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_delete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_delete.Click
Try
query = "DELETE FROM userinfo WHERER userid=" + txt_userid.Text
Dim mysqlcommand As New MySqlCommand(query, connection)
MsgBox(query)
Dim i As Integer = mysqlcommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is deleted")
Else
MsgBox("record is not deleted")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Your query seems to be syntactically correct, however, I would always use a parameterized query instead of a string concatenation. This will avoid Sql Injection and the quoting around the parameter value will be carried out by the framework code.
Try this for the update method
Try
query = "UPDATE USERINFO SET username=#uname, age=#uage WHERE userid = #uid";
Dim mysqlcommand = New MySqlCommand(query, connection)
mysqlcommand.Parameters.AddWithValue("#uname", txt_username.Text))
mysqlcommand.Parameters.AddWithValue("#uage",Convert.ToInt32(txt_age.Text))
mysqlcommand.Parameters.AddWithValue("#uid",Convert.ToInt32(txt_userid.Text))
Dim i As Integer = mysqlcommand.ExecuteNonQuery()
If (i > 0) Then
MsgBox("record is updated")
Else
MsgBox("record is not updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Another important thing to fix in your code is the global connection object. Don't do that. If one of your query fails for whatever reason you leave the connection open and that is a serious problem for the stability of your code.
Try
query = "UPDATE USERINFO SET username=#uname, age=#uage WHERE userid = #uid";
Using con = new MySqlConnection(.......)
Using cmd = new MySqlCommand(query, con)
con.Open()
cmd.Parameters.AddWithValue(......)
End Using
End Using
Catch ex As Exception
....
End Try
The using statement is critical to ensure a correct usage of expensive resources like a connection to the database and ensure a proper close and dispose of these kind of objects