MySqlDataReader giving error at build - mysql

I have a function in VB.NET that authenticates a user towards a MySQL database before launching the main application. Here's the code of the function:
Public Function authConnect() As Boolean
Dim dbserver As String
Dim dbuser As String
Dim dbpass As String
dbserver = My.Settings.dbserver.ToString
dbuser = My.Settings.dbuser.ToString
dbpass = My.Settings.dbpass.ToString
conn = New MySqlConnection
myConnString = "server=" & dbserver & ";" & "user id=" & dbuser & ";" & "password=" & dbpass & ";" & "database=rtadmin"
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim myData As New DataTable
Dim myDataReader As New MySqlDataReader
Dim query As String
myCommand.Parameters.Add(New MySqlParameter("?Username", login_usr_txt.Text))
myCommand.Parameters.Add(New MySqlParameter("?Password", login_pass_txt.Text))
query = "select * from users where user = ?Username and passwd = ?Password"
conn.ConnectionString = myConnString
Try
conn.Open()
Try
myCommand.Connection = conn
myCommand.CommandText = query
myAdapter.SelectCommand = myCommand
myDataReader = myCommand.ExecuteReader
If myDataReader.HasRows() Then
MessageBox.Show("You've been logged in.", "RT Live! Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
End Try
Catch ex As Exception
End Try
End Function
The function is not yet complete, there are a few other things that need to be done before launching the application, since I'm using a MessageBox to display the result of the login attempt.
The error that I'm getting is the following:
Error 1 'MySql.Data.MySqlClient.MySqlDataReader.Friend Sub New(cmd As MySql.Data.MySqlClient.MySqlCommand, statement As MySql.Data.MySqlClient.PreparableStatement, behavior As System.Data.CommandBehavior)' is not accessible in this context because it is 'Friend'. C:\Users\Mario\documents\visual studio 2010\Projects\Remote Techs Live!\Remote Techs Live!\Login.vb 43 13 Remote Techs Live!
Any ideas?

It makes no sense to try to create a MySqlDataReader and then throw it away!
First you do this to attempt to create a reader:
Dim myDataReader As New MySqlDataReader
Then later you attempt to throw that away when you do this:
myDataReader = myCommand.ExecuteReader
Just remove the New from your initial declaration. I suspect that the constructor for the MySqlDataReader is not publicly accessible.

You could try the .AddWithValue instead of .Add.
For example:
cmd.Parameters.AddWithValue("?Username", login_usr_txt.Text)

Related

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

VB.net Login with MySQL

I do not know what went wrong. Im new to vb. Can someone help me? Maybe correct my codes cause I've been spending so much time with this login form of mine. Thanks! here's my code.
By the way, I have a table with 3 columns. Username, Password and Privilege. Whenever I input my Login credentials, it only display the Msgbox Try again.
Imports MySql.Data.MySqlClient
Public Class LoginForm
Dim cn As New MySqlConnection
Dim cmd As MySqlCommand
Dim reader As MySqlDataAdapter
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim tblUser As New DataTable
Try
If PasswordTextBox.Text = "" Or UsernameTextBox.Text = "" Then
MessageBox.Show("Please provide your login credentials!")
Else
Dim sql As String
sql = "SELECT * from user_account where username = '" & UsernameTextBox.Text & "' and password = '" & PasswordTextBox.Text & "'"
Using con As New MySqlConnection(My.Settings.ConnectionString)
With cmd
.Connection = con
.CommandText = sql
End With
reader.SelectCommand = cmd
reader.Fill(tblUser)
If tblUser.Rows.Count > 0 Then
Dim userType As String
userType = tblUser.Rows(0).Item(2)
If userType = "admin" Then
MsgBox("Welcome, Admin!")
frmAdminMain.Show()
ElseIf userType = "encoder" Then
MsgBox("Welcome, User!")
MainForm.Show()
End If
Else
MsgBox("Invalid Credentials!")
End If
reader.Dispose()
End Using
End If
Catch ex As Exception
MsgBox("Try Again!")
End Try
End Sub
Add the "New" key word to your command declaration
Dim cmd As New MySqlCommand
"With" just set the properties, it does not initialize the object.

Connection must be valid and open VB.Net

I want to connect my MySQL to my VB.net.
I am only using Login Form.
I have given the code but the code gives me this error message: Connection must be valid and open
This is my code:
Imports MySql.Data.MySqlClient
Public Class Login
Dim MysqlConn As MySqlConnection
Dim Command As MySqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString ="server=db4free.net;port=3306;userid=exd****;password=****;database=exd****"
Dim Reader As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' "
Command = New MySqlCommand
Reader = Command.ExecuteReader
Dim count As Integer
count = 0
While Reader.Read
count = count + 1
End While
If count = 1 Then
MessageBox.Show("Correct !")
ElseIf count > 1 Then
MessageBox.Show("Duplicate !")
Else
MessageBox.Show("Not Correct !")
End If
MysqlConn.Close()
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
End Class
Can anyone help me to fix that? Thanks.
To associate your Query and Command with the connection you need to do this:
Command = New MySqlCommand(Query, MysqlConn)
You can then perform operations to retrieve the data you need.
At no point do you associate your MysqlConn nor Query to your Command before trying to call ExecuteReader on it. As such, it doesn't have a valid connection at that time.
Query = "select * from member where Username='" & UsernameTxt.Text & "' and Password='" & PasswordTxt.Text & "' ", nombredelaconexion

I would like to delete a row from a MySQL Database

The first part of the program, which reads the database works fine, the problem is with deleting. The database looks like: ID, Username and Text.
The code I'm currently using:
Public Class Form1
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim dr As MySqlDataReader
Private Sub Delete()
Try
dbCon = New MySqlConnection(Connection string)
strQuery = "Delete * FROM otletek WHERE id = " & TextBox2.Text
SQLCmd = New MySqlCommand(strQuery, dbCon)
dbCon.Open()
MsgBox(strQuery)
dbCon.Close()
Catch ex As Exception
MsgBox("Connection error" & vbCrLf & ex.Message)
End Try
End Sub
Are you missing the code that executes the SQL command?
SQLCmd.ExecuteNonQuery()
try this:
strQuery = "Delete FROM otletek WHERE id = " & TextBox2.Text
it's a SQL injection waiting to happen - bad idea.

Inserting VB.net Label to mysql table

How to Inserting Label.text data into mySql table.
i have no problem with textbox.text but i can't figure out how it with Label.text
i try the same code with textbox.text
parameterB_Answer.Value = TextBox1.Text
it work find but when i try with
parameterB_Answer.Value = Label1.Text
mySqlReader seems can't read it.
Update:
1.1.1 is label1.text. My Idea is to insert the text "1.1.1" from Label1 as Primary key and the Textbox(textbox1.text) as the following
my code is:
Try
Dim StrSQL As String = "INSERT INTO boranga" & _
"(IdBorangA,Answers)" & _
"VALUES (#B_IdA,#B_Answer);"
Dim myCommand As MySqlCommand = New MySqlCommand(StrSQL, conn.open)
myCommand.CommandType = CommandType.Text
Dim parameterB_IdA As MySqlParameter = New MySqlParameter("#B_IdA", MySqlDbType.VarChar, 300)
parameterB_IdA.Value = Label1.Text
Dim parameterB_Answer As MySqlParameter = New MySqlParameter("#B_Answer", MySqlDbType.VarChar, 300)
parameterB_Answer.Value = TextBox1.Text
With myCommand.Parameters
.Add(parameterB_IdA)
.Add(parameterB_Answer)
End With
Dim result As MySqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
MsgBox("Tersimpan", vbYes, "boranga")
Catch SqlEx As MySqlException
Throw New Exception(SqlEx.Message.ToString())
End Try
but when I change the value of Label1.text (1.1.1) to 111, it works just fine. probably because I put INT for the column for label1.text to fill while "1.1.1" isn't integer
thank a lot
PS:seems i can't post image because low of reputation
Try using this code format first of all:
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim conn As MySqlConnection
'Connect to the database using these credentials
conn = New MySqlConnection
conn.ConnectionString = "server=your server site (generally long url); user id=login id for mysql user; password=self explanatory; database=name of the DB you're trying to reach"
'Try and connect (conn.open)
Try
conn.Open()
Catch myerror As MySqlException 'If it fails do this... (i.e. no internet connection, etc.)
MsgBox("Error connecting to database. Check your internet connection.", MsgBoxStyle.Critical)
End Try
'MySQL query (where to call for information)
Dim myAdapter As New MySqlDataAdapter
'Tell where to find the file with the emails/passes stored
Dim sqlquery = "SELECT * FROM the database you selected above WHERE Email = '" & txtEmail.Text & "' AND Password = '" & txtPassword.Text & "'"
Dim myCommand As New MySqlCommand
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'Start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows = 0 Then
MsgBox("Invalid email address or password.", MsgBoxStyle.Critical)
Else
MsgBox("Logged in as " & txtEmail.Text & ".", MsgBoxStyle.Information)
Me.Close()
End If
End Sub
And to insert label.text try replacing one of the textbox.text fields first and see if it will accept it. If it does, then the answer was all in the formatting.
Also, do not forget to call:
imports mysql.data.mysqlclient
and make sure to add the mysql.data reference.