InvalidOperationException ocurred - mysql

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.

Related

vb.net cannot connect to sql server

I am trying to make a login database using vb.net. I am using this code to connect but it doesn't work!:
Public Class Form1
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
con.ConnectionString = "Data Source=localhost; Initial Catalog=user; Integrated Security= true"
cmd.Connection = con
con.Open()
cmd.CommandText = "select login, password from auth where login= '" & TextBox1.Text & "' and password = '" & TextBox2.Text & "' "
rd = cmd.ExecuteReader
If rd.HasRows Then
Welcome.Show()
Else
MessageBox.Show("Login Failed", "error")
End If
End Sub
End Class
I have a data base on my sql server called "user" and in user there is a table named "dbo.auth". When I click Label2, visual basic says "con cannot be opened" I am using MySQL server workbench. Is there any way I can fix this? The server is also running on my local network.
Does this work for you?
Imports System.Data.SqlClient
Public Class LoginForm1
Dim conn As SqlConnection
' TODO: Insert code to perform custom authentication using the provided username and password
' (See http://go.microsoft.com/fwlink/?LinkId=35339).
' The custom principal can then be attached to the current thread's principal as follows:
' My.User.CurrentPrincipal = CustomPrincipal
' where CustomPrincipal is the IPrincipal implementation used to perform authentication.
' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
' such as the username, display name, etc.
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
conn = New SqlConnection
conn.ConnectionString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"
Try
conn.Open()
MsgBox("Connected!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Also, I think you should bookmark the link below.
https://www.connectionstrings.com/

How do I write to a Mysql database in VB.net with a query

I am trying to make a little program that writes and reads from a Mysql database. The reading part is going well, but I am a bit stuck in the write part.
This is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Absenden.Click
Dim conn As New MySqlConnection
Dim command As MySqlCommand
Dim myConnectionString As String
myConnectionString = "server=Nothing;uid=to;pwd=see;database=here;"
conn.ConnectionString = myConnectionString
Try
conn.Open()
Dim Querywrite As String
Querywrite = "select * FROM here.message INSERT INTO message admin='" & TB_Name.Text & "' and message='" & TB_Nachricht.Text & "' and Server='" & TB_Server.Text & "' and status='" & TB_Status.Text & "' "
command = New MySqlCommand(Querywrite, connection)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
conn.Close()
End Sub
The Querywrite part is the problem I think. The input comes from Textboxes in a Windows Form.
Thanks for your help!
Perhaps, if someone shows you once then you will get the idea. The main thing is to always use parameters; not only will you avoid minor sytax and type errors but you will avoid major disasters of malicious input. I guessed at the datatypes of your fields. Please check your database for the types and adjust your code accordingly.
Private Sub InsertData()
Dim strQuery As String = "Insert Into message (admin, message, Server, status) Values (#admin, #message, #Server, #status);"
Using cn As New MySqlConnection("your connection string")
Using cmd As New MySqlCommand With {
.Connection = cn,
.CommandType = CommandType.Text,
.CommandText = strQuery}
cmd.Parameters.Add("#admin", MySqlDbType.VarString).Value = TB_Name.Text
cmd.Parameters.Add("#message", MySqlDbType.VarString).Value = TB_Nachricht.Text
cmd.Parameters.Add("#Server", MySqlDbType.VarString).Value = TB_Server.Text
cmd.Parameters.Add("#status", MySqlDbType.VarString).Value = TB_Status.Text
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
End Using
End Using
End Sub

MySQL login works for me but not my friend using VB

I have a program that takes info from the user and logs them into a database using Phpmyadmin, our code is the exact same, except for my friend he can't login.
Code is here:
Both our database name, tables and columns are the EXACT same, he can register the account to the DB so it stores it, but when he tries to login with the same information it says that it was unsuccessful.
SignUpForm(THIS WORKS)
Public Class frmSignup
Dim ServerString As String = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MsgBox("Successfully connected to DB")
Else
SQLConnection.Close()
MsgBox("Failed to connect to DB")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveAccountInformation(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
SQLConnection.Dispose()
End Sub
Private Sub btnSignup_Click(sender As Object, e As EventArgs) Handles btnSignup.Click
If txtPasswd.Text = txtPasswd2.Text Then
MessageBox.Show("Passwords Match!")
Dim HashedPass As String = ""
'Converts the Password into bytes, computes the hash of those bytes, and then converts them into a Base64 string
Using MD5hash As MD5 = MD5.Create()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(txtPasswd.Text)))
End Using
Dim SQLStatement As String = "INSERT INTO accountinfodb(`Usernames`, `Passwords`) VALUES ('" & txtUsername.Text & "','" & HashedPass & "')"
SaveAccountInformation(SQLStatement)
MessageBox.Show("Account Successfully Registered")
frmLogin.Show()
frmLoginScreen.Hide()
Else
MessageBox.Show("Passwords Do Not Match!")
txtPasswd.Text = Focus()
txtPasswd.Clear()
txtPasswd2.Text = Focus()
txtPasswd2.Clear()
End If
End Sub
End Class
LOGIN FORM(THIS DOES NOT WORK FOR HIM BUT IT WORKS FOR ME)
Imports MySql.Data.MySqlClient
Imports System.Security.Cryptography
Public Class frmLogin
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim conStr = "Server=localhost;User Id=root;Password=;Database=accountinfo"
Dim SQL = "SELECT * FROM accountinfodb WHERE Usernames = #uname AND `Passwords` = #pword"
Dim HashedPass As String = ""
'Converts the Password into bytes, computes the hash of those bytes, and then converts them into a Base64 string
Using MD5hash As MD5 = MD5.Create()
HashedPass = System.Convert.ToBase64String(MD5hash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(txtPasswd.Text)))
End Using
' this object will be closed and dispose # End Using
Using dbCon As New MySqlConnection(conStr)
' the command object likewise
Using cmd As New MySqlCommand(SQL, dbCon)
dbCon.Open()
cmd.Parameters.Add(New MySqlParameter("#uname", txtUsername.Text))
cmd.Parameters.Add(New MySqlParameter("#pword", HashedPass))
' create a Using scope block for the reader
Using rdr As MySqlDataReader = cmd.ExecuteReader
If rdr.HasRows Then
MessageBox.Show("Welcome, " & txtUsername.Text)
frmProduct.Show()
Else
MessageBox.Show("Oops! Login unsuccessful!(Password/Username may be wrong, or the user may not exist!")
txtUsername.Clear()
txtUsername.Focus()
txtPasswd.Clear()
End If
End Using
End Using ' close/dispose command
End Using ' close/dispose connection
End Sub
End Class
WOULD ALSO LIKE TO MENTION
I shared my files over google drive with him, so he did not copy and paste any of the code. This is the exact same files from MY computer.
Ok I found the issue, he was using an outdated version of MySQL while my version was the most up to date. I reinstalled the proper MySQL server to the newest version and it worked!

update query not working when i attach the content of text box using data reader on page load

Code works fine when i remove the page load content. this is a form which will allow user to edit the data already present in database. i just want to let a user edit a form which he have already submitted.
This is the code:
Dim con As New SqlConnection("Data Source=ENCODER-PC\SQLEXPRESS;Integrated Security=True")
Dim cmd, com As New SqlCommand
Dim dr As SqlDataReader
Dim n, d, a As Integer
Dim returnValue As Object
Dim str As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
str = "select * from School where RollNo=11"
com = New SqlCommand(str, con)
dr = com.ExecuteReader()
con.Open()
If (dr.Read()) Then
Enroll.Text = dr("RollNo").ToString()
Name.Text = dr("Name").ToString()
Class.Text = dr("Class").ToString()
End If
con.Close()
dr.Close()
End Sub
Protected Sub Next_Click(sender As Object, e As EventArgs) Handles [Next].Click
Try
cmd.CommandText = "Update School SET RollNo='" & Enroll.Text & "', Name='" & Name.Text & "', Class='" & Class.Text & "' where RollNo=11 "
cmd.Connection = con
con.Open()
MsgBox("Connection is Open ! ")
n = cmd.ExecuteNonQuery
If n > 0 Then
MsgBox("data inserted successfully")
Else
MsgBox("data insertion failed")
End If
Catch ex As Exception
MsgBox(ex.ToString())
Finally
con.Close()
End Try
End Sub
You have tagged your question with MySql but in code you use the classes for Sql Server and a connection string specific to Sql Server.
So you should clarify this point. However, in the meantime I wish to give an answer to some errors in your Page_Load event handler:
First you need to check if the call to Page_Load is a postback from other controls and avoid to reload the data from the database in that case. See ASP.NET Page Life Cycle
Second, open the connection before executing the reader
Dim constring = "Data Source=ENCODER-PC\SQLEXPRESS;Integrated Security=True"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim str = "select * from School where RollNo=11"
If Not IsPostBack Then
Using con = new SqlConnection(conString)
Using cmd = new SqlCommand(str, con)
con.Open()
Using dr = com.ExecuteReader()
If (dr.Read()) Then
Enroll.Text = dr("RollNo").ToString()
Name.Text = dr("Name").ToString()
Class.Text = dr("Class").ToString()
End If
End Using
End Using
End Using
End If
End Sub
As you can see there are other improvements: No more global variables for connection, command and reader and Using Statement around the disposable objects.
If this code is really intended to run against a MySql database then you need to use the appropriate classes like MySqlConnection, MySqlCommand, MySqlDataReader etc.. and fix the connectionstring

InvalidArgument=Value of '11209485' is not valid for 'index'. Parameter name: index error when running SQL query in VB.NET

I keep getting this error "Failure to communicate InvalidArgument=Value of '11209485' is not valid for 'index'. Parameter name: index" when I'm trying to retrieve card numbers from a database and put them in a combo box so that the user can pick their card number in VB.NET 2012. The 11209485 is the first card number in the database, so I assume the connection is fine, but I don't understand this error at all.
I'd be grateful for any help on the matter. Thanks!
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class Form1
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLcmd As MySqlCommand
Dim DataReader As MySqlDataReader
' load application Form
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'Prepare connection and query
Try
dbCon = New MySqlConnection("Server=localhost;Database=***;Uid=***;Pwd=***")
strQuery = "SELECT CardNumber " &
"FROM Account"
SQLcmd = New MySqlCommand(strQuery, dbCon)
'Open the connection
dbCon.Open()
' create database reader to read information from database
DataReader = SQLcmd.ExecuteReader
' fill ComboBox with account numbers
While DataReader.Read
cboAccountNumbers = cboAccountNumbers.Items(DataReader("CardNumber"))
End While
'Close the connection
DataReader.Close()
dbCon.Close()
Catch ex As Exception
MsgBox("Failure to communicate" & vbCrLf & vbCrLf & ex.Message)
End Try
End Sub
End Class
The error is in this line:
cboAccountNumbers = cboAccountNumbers.Items(DataReader("CardNumber"))
You are attempting to read the 11209485th item in the combo box and there aren't that many items. Try this instead:
cboAccountNumbers.Items.Add(DataReader("CardNumber"))