Error when getting MySQL data in .NET - mysql

I'm creating a .NET web application that retrieves data from a database. I keep getting the following error when running the below code though.
Fatal error encountered during command execution.
The InnerException is {"Parameter '?Username' must be defined."}, but I can see that ?Username is defined and I know that Session("Username") is correct and exists.
Here is the code. It fails on the SupervisorNameAdapter.Fill(SupervisorNameData, "Data") line.
Dim SupervisorID As String = Session("Username")
Dim qryGetSupervisorName As String = "select * from USERS where UserID = ?Username"
Using cn As New MySqlConnection(ConfigurationManager.ConnectionStrings("ConnectionInfo").ConnectionString), cmd As New MySqlCommand(qryGetSupervisorName, cn)
cmd.Parameters.AddWithValue("?Username", SupervisorID)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Dim SupervisorNameAdapter As New MySqlDataAdapter(qryGetSupervisorName, cn)
Dim SupervisorNameData As New DataSet
SupervisorNameAdapter.Fill(SupervisorNameData, "Data")
If SupervisorNameData.Tables(0).Rows.Count = 0 Then
MsgBox("An error has occured. Please refresh the page.", vbOKOnly, "Error!")
Else
SupervisorName.Text = SupervisorNameData.Tables(0).Rows(0).Item(1) & " " & SupervisorNameData.Tables(0).Rows(0).Item(2)
End If
End Using
Does anyone know why this is happening?

You are not setting correctly the command to be used by the MySqlAdapter. You just pass the command text string and with that string the adapter build another command that is missing the required parameter
Just change your code to
Dim SupervisorID As String = Session("Username")
Dim qryGetSupervisorName As String = "select * from USERS where UserID = ?Username"
Using cn As New MySqlConnection(ConfigurationManager.ConnectionStrings("ConnectionInfo").ConnectionString), cmd As New MySqlCommand(qryGetSupervisorName, cn)
cmd.Parameters.AddWithValue("?Username", SupervisorID)
Dim SupervisorNameAdapter As New MySqlDataAdapter(cmd)
Dim SupervisorNameData As New DataSet
....
End Using

Related

VB.NET MySQL : Error 'Unable to cast object of type 'System.Int32' to type 'MySql.Data.MySqlClient.MySqlDataReader

I have trouble with my coding below :
Private Function NoCustID() As String
Dim drtmp As MySqlDataReader
Dim mySqlCmd As New MySqlCommand
Dim sTmp As String
Dim nStr As String
dbConn.Open()
sTmp = "SELECT * FROM tbnomor WHERE ftipe=1 AND UPPER(fnama)='CUSTOMER'"
mySqlCmd = New MySqlCommand(sTmp, dbConn)
drtmp = mySqlCmd.ExecuteScalar()
nStr = drtmp("fprefix").ToString & "-" & String.Format(drtmp("ftempno").ToString, "0000")
dbConn.Close()
Return nStr
End Function
Error raised on Line With ExecuteScalar(), where the error code as shown above title.
I don't know what mistake.
Please help, thanks
Change drtmp = mySqlCmd.ExecuteScalar() to drtmp = mySqlCmd.ExecuteReader().
The method ExecuteScalar() returns the first column of the first row in the result and ignore others. In this instance, the returned column is integer data type, and not an array.
Use:
drtmp = mySqlCmd.ExecuteReader()
While drtmp.Read()
nStr = drtmp("fprefix").ToString & "-" & String.Format(drtmp("ftempno").ToString, "0000")
End While
Don't declare connections outside of the method where they are used. Both connections and commands need to be disposed. Using...End Using blocks handle this for us.
Don't open the connection until directly before the .Execute...
.ExecuteScalar is used to return a single piece of data. You need .ExecuteReader to return a DataReader.
Don't process data until the connection is closed with End Using.
I filled a DataTable so your could process the data after the connection is closed. Readers require an open connection.
Private ConStr As String = "Your connection string"
Private Function NoCustID() As String
Dim dt As New DataTable
Using dbConn As New MySqlConnection(ConStr),
mySqlCmd As New MySqlCommand("SELECT * FROM tbnomor WHERE ftipe=1 AND UPPER(fnama)='CUSTOMER'", dbConn)
dbConn.Open()
Using drtmp = mySqlCmd.ExecuteReader
dt.Load(drtmp)
End Using
End Using
Dim nStr = $"{dt(0)("fprefix")} - {dt(0)("ftempno"):0000}"
Return nStr
End Function

How to read a value from mysql database?

I want to be able to read a value (in this case an Group ID). All the topics and tutorials I've watched/read take the data and put it into a textbox.
I don't want to put it in a textbox in this case; I want to grab the Group ID and then say:
If Group ID = 4 then login
Here is an image of the database.
Basically, but none of the tutorials I watch or the multiple forums. None of them take a a value and say if value = 4 then login or do something else.
If text = "1" Then
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server='ip of server'.; username=; password=; database="
Dim READER As MySqlDataReader
Dim member_group_id As String
Try
MysqlConn.Open()
Dim Query As String
Query = "SELECT * FROM `core_members` where name='" & TextBox2.Text & "'"
Query = "SELECT * FROM `nexus_licensekeys` where lkey_key='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
Here is what I have so far. I'm kind of new implementing mysql data with visual basic and only recently started to get into it. I'm not sure what comes next or how to even start with reading the group id etc.
As I said any help from here on out would be highly appreciated of how to read the group id and say if this group id = this number then do this or that. I'm sure you get the idea.
I divided the code into UI Sub, and Data Access Function that can return data to the UI. Your Event procedure code should be rather brief and the functions should have a single purpose.
Keep your database objects local to the method. This way you can have better control. The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I leave it to you to add validation code. Checking for empty TextBox or no return of records.
I hope this serves as a quick introduction to using ADO.net. The take away is:
Use Parameters
Make sure connections are closed. (Using blocks)
Private ConnString As String = "server=ip of server; username=; password=; database="
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GroupID As String = GetGroupID(TextBox1.Text)
If GroupID = "4" Then
'your code here
End If
Dim LocalTable As DataTable = GetLicenseKeysData(TextBox1.Text)
'Get the count
Dim RowCount As Integer = LocalTable.Rows.Count
'Display the data
DataGridView1.DataSource = LocalTable
End Sub
Private Function GetGroupID(InputName As String) As String
'Are you sure member_group_id is a String? Sure looks like it should be an Integer
Dim member_group_id As String = ""
'You can pass the connection string directly to the constructor of the connection
Using MysqlConn As New MySqlConnection(ConnString)
'If you only need the value of one field Select just the field not *
'ALWAYS use parameters. See comment by #djv concerning drop table
Using cmd As New MySqlCommand("SELECT g_id FROM core_members where name= #Name")
'The parameters are interperted by the server as a value and not executable code
'so even if a malicious user entered "drop table" it would not be executed.
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
MysqlConn.Open()
'ExecuteScalar returns the first column of the first row of the result set
member_group_id = cmd.ExecuteScalar.ToString
End Using
End Using
Return member_group_id
End Function
Private Function GetLicenseKeysData(InputName As String) As DataTable
Dim dt As New DataTable
Using cn As New MySqlConnection(ConnString)
Using cmd As New MySqlCommand("SELECT * FROM `nexus_licensekeys` where lkey_key= #Name;", cn)
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = InputName
cn.Open()
dt.Load(cmd.ExecuteReader())
End Using
End Using
Return dt
End Function

mysql select statement not filling datatable

I have a MySQL object I am trying to select all data from and insert into a datatable however every time it gets to my first if statement regarding said datatable It gets a possible null value error
dbfile dbserver dbuser and dbpassw all are public variables set on on a module.
variable dimensions
Dim cnn As New MySqlConnection()
Dim cmd As New MySqlCommand
Dim adptr As New MySqlDataAdapter
Dim filltab As DataTable
code
Dim cb As New MySqlConnectionStringBuilder
cb.Database = dbfile
cb.Server = dbserver
cb.UserID = dbuser
cb.Password = dbpassw
Using cnn As New MySqlConnection(cb.ConnectionString)
Using cmd As New MySqlCommand("SELECT * from gpstracking", cnn)
Try
cnn.Open()
adptr = New MySqlDataAdapter(cmd)
adptr.Fill(filltab)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
If filltab.Rows.Count > 0 Then 'this is the row that the error for filltab being a null value hits
pop = 0
For pop As Integer = 0 To filltab.Rows.Count - 1
' WebBrowser1.Document.InvokeScript("AddMarker", New Object() {"Unit: " & filltab.Rows(pop)("unitnumb") & " at " & filltab.Rows(pop)("time"), filltab.Rows(pop)("lat"), table.Rows(pop)("long")})
Next
End If
End Using
End Using
one error on
adptr.Fill(filltab) 'Exception:Thrown: "Value cannot be null." (System.ArgumentNullException)
I also just noticed it is announcing "failure to collect details" on
Catch ex As Exception
MsgBox(ex.ToString)
End Try
I don't know vb syntax, but you have Dim filltab As DataTable without New (like in other dimensions), and I guess MySqlDataAdapter.Fill requires the argument to be not null. Just a guess.
instead of using this code
adptr = New MySqlDataAdapter(cmd)
adptr.Fill(filltab)
try use
filltab.load(cmd.ExecuteReader())

String from Database set as public string

Ok from the answer from the previous question the reasoning still applies here but this time A different issue. There is a login system (Loginvb.vb) that I got for the launcher I was creating and was wondering 2 things:
Is there a better way to do the Login check with the database (as in
more secure) (the login style will have a web based registration
setting via PHP script)?
Is there a way to take a certain column (labled as access) in the database and put it
as a public string so I can check if it will equal 1 2 or 3 in a
different form labeled as Main.vb
Here is the current login check:
Public Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
If txtuserName.Text = "" Or txtpassWord.Text = "" Then
MsgBox("You cannot progress until you login....(moron =p)")
Else
'Connects To the Database
Dim connect As MySqlConnection
connect = New MySqlConnection()
connect.ConnectionString = "server=127.0.0.1;user id=sc;Password=derp;database=sclaunch" 'not the actual login ;)
Try
connect.Open()
Catch myerror As MySqlException
MsgBox("Error Connecting to Database. Please Try again !")
End Try
'SQL Query To Get The Details
Dim myAdapter As New MySqlDataAdapter
Dim sqlquerry = "Select * From login where username = '" + txtuserName.Text + "' And password= '" + txtpassWord.Text + "'"
Dim myCommand As New MySqlCommand()
'My fail attempt at what I am trying to do :(
Dim sql22 As MySqlConnection
sql22 = New MySqlConnection()
sql22.ConnectionString = "Select * From login where access ="
'End of fail attempt
myCommand.Connection = connect
myCommand.CommandText = sqlquerry
'Starting The Query
myAdapter.SelectCommand = myCommand
Dim mydata As MySqlDataReader
mydata = myCommand.ExecuteReader
'To check the Username and password and to validate the login
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
Else
'fail testing xD
Label3.Text = sql22
MsgBox("You are now Loged In!")
End If
End If
End Sub
Still basically learning more and more as I am coding all this got to love trial and error and the moments where you get stuck =/ (Sorry to the admins or whatever for fixing tag issues still new to the site xD)
Assuming that the same table login that contains the credentials contains also the access column that you want to retrieve, then I have changed a lot of your code
Dim sqlquerry = "Select * From login where username = #name AND password=#pwd"
Dim myCommand As New MySqlCommand(sqlquery, connect)
myCommand.Parameters.AddWithValue("#name", txtuserName.Text)
myCommand.Parameters.AddWithValue("#pwd", txtpassWord.Text)
Dim mydata = myCommand.ExecuteReader
If mydata.HasRows = False Then
MsgBox("Invalid Login")
Else
' the same record that contains the credentials contains the access field'
mydata.Read()
Label3.Text = mydata("access").ToString()
MsgBox("You are now Loged In!")
End If
What I have changed:
Removed the string concatenation and added the appropriate parameters
Removed myAdapter and every references to it (not needed, you don't
fill DataTable/DataSet)
Removed sql22 and every references to it. It's a Connection and you
try to use like a Command
Fixed the check on HasRows (Returns a boolean not an integer. Are you
using Option Strict Off?)

querying a MySQL table from VB.NET

I made my software in vb.net and connected it with MySQL databse and using phpmyadmin I have create a table update and a column version.
In the version column I have inserted the link of version.txt
I want that my update library which is updateVB will get the link of version.txt from the database from that table....
Updatevb1.checkforupdate("Text file where your version is stated (URL)",
"Current Version",
"URL of executable updater (SFX Archive),
"Username for FTP", "Password for FTP",
showUI As Boolean)
I want to get every of these information like: Text file version URL, current version, URL of executable update etc.
How can this be done?
conn = New MySqlConnection(ServerString)
Try
conn.Open()
Dim sqlquery As String = "SELECT FROM updater"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() Then
Dim vlink As String = data(1).ToString
Dim dlink As String = data(2).ToString
Dim ftpu As String = data(3).ToString
Dim ftpp As String = data(4).ToString
End If
End While
UpdateVB1.checkforupdate("vlink", "0.0.9", "dlink", "ftpu", "ftpp", showUI:=True)
data.Close()
conn.Close()
The first problem is that your SQL statement isn't specifying any columns.
Supply the list of columns that you want to consume.
Dim sqlquery As String = "SELECT vlink, dlink, ftpu, dtpp FROM updater"