Why do I keep getting this mysql error? - mysql

Hi stackoverflow people!
I have been recently developing a simple vb.net program that connects to a mysql database to register and login users with given credentials. I have used this code to register my users but I keep getting and error (below the code)
Dim insertUser As String = "INSERT INTO users(ID, username, password, email, verif)" _
& " VALUES('','" & Username.Text & "','" & Password.Text & "','" & Email.Text & "','" & currentRandString & "');"
Dim checkUsername As String = "SELECT * FROM users WHERE username='" & Username.Text & "'"
MysqlConn = New MySqlConnection()
MysqlConn.ConnectionString = mysqlconntxt4reg
MysqlConn.Open()
Dim myCommand As New MySqlCommand
myCommand.Connection = MysqlConn
myCommand.CommandText = checkUsername
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
myData.Close()
Else
myData.Close()
Dim myCommand2 As New MySqlCommand
myCommand2.Connection = MysqlConn
myCommand2.CommandText = insertUser
myAdapter.SelectCommand = myCommand2
Dim myData2 As MySqlDataReader
myData2 = myCommand2.ExecuteReader
Mail(Email.Text, currentRandString)
Me.Close()
myData2.Close()
End If
Catch myerror As MySqlException
MsgBox("Error While Connecting To Database:" & vbNewLine & vbNewLine & myerror.ToString, MsgBoxStyle.Critical, "Error")
Finally
MysqlConn.Dispose()
End Try
I have closed all my datareaders before opening other ones so I do not see why this does not work...
Error:
Link to Error Image
I would appreciate any help on this topic!
Thanks
Rodit

I would use the using statement around all the disposable objects to be sure that they release every references to the connection when they are no more needed, but looking at your code, I think you don't need at all the datareaders because you could resolve your problem just with the commands
Dim insertUser As String = "INSERT INTO users(username, password, email, verif)" _
& " VALUES(#p1, #p2,#p3,#p4)"
Dim checkUsername As String = "SELECT COUNT(*) FROM users WHERE username=#p1"
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
myCommand.Parameters.AddWithValue("#p1", Username.Text)
Dim result = myCommand.ExecuteScalar()
if result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
Else
Using myCommand2 = New MySqlCommand(insertUser, MysqlConn)
mycommand2.Parameters.AddWithValue("#p1",Username.Text)
mycommand2.Parameters.AddWithValue("#p2",Password.Text )
mycommand2.Parameters.AddWithValue("#p3",Email.Text)
mycommand2.Parameters.AddWithValue("#p4",currentRandString )
myCommand2.ExecuteNonQuery()
Mail(Email.Text, currentRandString)
End Using
End If
End Using
End Using
Of course I have replaced your string concatenations with a parameterized query. This is really an important thing to do to avoid Sql Injection
I have replaced the query that checks the user existence with a scalar operation that can be used with the command ExecuteScalar. Also, in the first query, it seems that you try to insert the field ID with an empty string. I think that the first field (ID) is an autonumber field and, in this case, you don't add it to the insert query and don't pass any value because the database will calculate that field for you.

Related

Making an error message for the repeating in or out if loops in the database table [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Good Day, to make things clear I will introduce my ongoing system which is "Gate attendance for student in our university", this system is consists of RFID reader RC522 and Arduino, the student should tap his/her RFID tag and the data retrieved shown at the monitor.. The system is our capstone project and it is done but the panel required us for another problem to be solved.
All functions is already done about the scanning,retrieving data,registering students , this will apply to the college students which is feel free to go out and in anytime depends on the schedule unlike highschool just one IN and OUT.
The two RFID reader is placed in Entrance and Exit of the University theres a system for out in the exit and In for the entrance.The data retrieved from in and out would save into the same table.
How can I show the messagebox warning to the students if he taps IN without go OUT first? I know it something about the query. but I have no Idea. I need some help here for my Capstone.. Any Comments and suggestion is appreciated advance.. Here is my code about the retrieving the data based on the RFID tag number shown in the textbox changed event..by the way my table studlogs is the one handled the attendance.
Private Sub studtag_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles studtag.TextChanged
Notenrolled.Close()
greet.Text = ""
PictureBox4.Visible = False
If studtag.Text = "44F2F38B" Then
Endday()
End If
If studtag.Text = recents.Text Then
Alreadylogin.Show()
ElseIf studtag.TextLength = 8 Then
DataGridView1.Sort(DataGridView1.Columns(6), System.ComponentModel.ListSortDirection.Descending)
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Dim query As String
query = "select * from dat.students"
cmd = New MySqlCommand(query, con)
Dim table As New DataTable
Try
con.Open()
'Gets or sets an SQL statement or stored procedure used to select records in the database.
With cmd
.Connection = con
.CommandText = "SELECT * from students where `studtags`='" & studtag.Text & "';"
End With
da.SelectCommand = cmd
da.Fill(table)
'it gets the data from specific column and fill it into Label
idno.Text = table.Rows(0).Item(1)
lastxt.Text = table.Rows(0).Item(2)
firstxt.Text = table.Rows(0).Item(3)
middletxt.Text = table.Rows(0).Item(4)
dob.Text = table.Rows(0).Item(6)
year.Text = table.Rows(0).Item(7)
crsetxt.Text = table.Rows(0).Item(10)
tagtxt.Text = studtag.Text
timein.Text = times.Text
dr = cmd.ExecuteReader()
dr.Read()
If dob.Text = bday.Text Then
greet.Text = firstxt.Text + " Today is your Birthday. Greetings :D."
PictureBox4.Visible = True
End If
Dim img() As Byte = CType(dr("studpic"), Byte())
Using ms As New IO.MemoryStream(img)
PictureBox1.Image = Image.FromStream(ms)
End Using
My.Computer.Audio.Play("C:\Users\BOR\Desktop\Parsu Gate\Parsu\audio\scanned.wav")
insert()
loadtable()
studdailyhistory()
Catch ex As Exception
Notenrolled.Show()
DataGridView1.Sort(DataGridView1.Columns(5), System.ComponentModel.ListSortDirection.Descending)
If studtag.Text = "44F2F38B" Then
Notenrolled.Close()
End If
Finally
con.Dispose()
con.Close()
End Try
End If
recents.Text = tagtxt.Text
End Sub
Public Sub insert()
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Dim reader As MySqlDataReader
Dim mstream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
Try
con.Open()
Dim query3 As String
query3 = "insert into dat.studlogs (studtags,idno,lastxt,firstxt,middletxt,dob,log,timein,crse,studpic) values ('" & tagtxt.Text & "','" & idno.Text & "','" & lastxt.Text & "','" & firstxt.Text & "','" & middletxt.Text & "','" & dob.Text & "','" & log.Text & "','" & timein.Text & "','" & crsetxt.Text & "',#studpic)"
cmd = New MySqlCommand(query3, con)
cmd.Parameters.AddWithValue("#studpic", arrImage)
reader = cmd.ExecuteReader
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Public Sub studdailyhistory()
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Dim reader As MySqlDataReader
Dim mstream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
Try
con.Open()
Dim query3 As String
query3 = "insert into dat.studdailyhistory (studtags,idno,lastxt,firstxt,middletxt,dob,log,timein,crse,dates,studpic) values ('" & tagtxt.Text & "','" & idno.Text & "','" & lastxt.Text & "','" & firstxt.Text & "','" & middletxt.Text & "','" & dob.Text & "','" & log.Text & "','" & timein.Text & "','" & crsetxt.Text & "','" & wholedate.Text & "',#studpic)"
cmd = New MySqlCommand(query3, con)
cmd.Parameters.AddWithValue("#studpic", arrImage)
reader = cmd.ExecuteReader
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Public Sub loadtable()
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Dim SDA As New MySqlDataAdapter
Dim dbDataset As New DataTable
Dim bSource As New BindingSource
Try
con.Open()
Dim query3 As String
query3 = "select idno as 'Student_ID',lastxt as 'LastName',firstxt as 'FirstName',middletxt as 'MiddleName',log as 'Status',timein as 'Timein',crse as 'Course' from dat.studlogs"
cmd = New MySqlCommand(query3, con)
SDA.SelectCommand = cmd
SDA.Fill(dbDataset)
bSource.DataSource = dbDataset
DataGridView1.DataSource = bSource
SDA.Update(dbDataset)
DataGridView1.Sort(DataGridView1.Columns(5), System.ComponentModel.ListSortDirection.Descending)
If dbDataset.Rows.Count > 0 Then
logins.Text = dbDataset.Rows.Count.ToString()
End If
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
I am not sure i understand properly, but i guess u dont want the student be able to clock in twice without clock out.
You have multiple options.
The simpliest, you can use a status field in your db. When student clock in then save "status"=1 (student onsite), and at clockout "status"=0 (student not onsite). At every clock in and clock out you check the status of student. If 1 then can't clock in again as she/he onsite already.
Or you save in the log when they tap the fob it was an entrance or leave and when you query the table with student you order the table by last insert time so the last record will come up where you see the last status of the log.
Edit:
Add an extra bool type column in your database to students table like "studOnsite" and set the default value 0. When a student scan a card and you get the student details from the table here :
.CommandText = "SELECT * from students where `studtags`='" & studtag.Text & "';"
You will get back the "studOnsite" column aswell. After you can simply check the value like :
if (table.Rows(0).Item("studOnsite") then
'student already onsite so she/he is leaving
greet.Text = firstxt.Text & "Good bye!"
'update the student table and change "studOnsite" to false
'dim query as string=string.format("UPDATE students SET studOnsite=false WHERE studtags='{0}'",studtag.Text)
else
'student wasn't onsite so she/he is just arrived
greet.Text = firstxt.Text & "Welcome back!"
'update the student table and change "studOnsite" to true as student is onsite now
'dim query as string=string.format("UPDATE students SET studOnsite=true WHERE studtags='{0}'",studtag.Text)
end if

inserting data on mysql using vb.net with VS2010

im trying to insert data in mysql but i just cant do it ive tried to search for answers on the net and tried everything on my code but it just wont insert here is the image of the error
hope some one can help me and thanks in advance ... MERRY CHRISTMAS !!
here is the code
myconn = New MySqlConnection
myconn.ConnectionString = "host=127.0.0.1;user=root;password=;database=engr_log"
Dim Reader As MySqlDataReader
Try
myconn.Open()
Dim query As String
query = "insert into log_tbl ('ID', 'owner_name', 'business_name', 'Amount_paid', 'Location', 'Date') values (NULL, '" & txtname.Text & "','" & txtbus.Text & "','" & txtamount.Text & "', '" & txtloc.Text & "','" & dtp1.Value & "');"
command = New MySqlCommand(query, myconn)
Reader = command.ExecuteReader
MessageBox.Show("Entry Saved!!","SAVE", MessageBoxButtons.OK, MessageBoxIcon.Information)
myconn.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
getlist()
End Sub
Remove the single quotes around the column in your insert statment:
insert into log_tbl (ID, owner_name, business_name, Amount_paid, Location, Date)...
But the bigger problem is you should use queries with parameters to not only avoid errors but also SQL injections.
Example:
Dim connectionString = "host=127.0.0.1;user=root;password=;database=engr_log"
Dim query = "insert into log_tbl (owner_name, business_name, Amount_paid, Location, Date) values (#owner_name, #business_name, #Amount_paid, #Location, #Date);"
Using connection As New MySqlConnection(connectionString)
Dim command As New MySqlCommand(query, connection)
command.Parameters.AddWithValue("#owner_name", txtname.Text)
command.Parameters.AddWithValue("#business_name", txtbus.Text)
command.Parameters.AddWithValue("#Amount_paid", txtamount.Text)
command.Parameters.AddWithValue("#Location", txtloc.Text)
command.Parameters.AddWithValue("#Date", dtp1.Text)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
Even better, you can be explicit with the types:
command.Parameters.Add("#owner_name", SqlDbType.VarChar)
command.Parameters.Add("#business_name", SqlDbType.VarChar)
command.Parameters.Add("#Amount_paid", SqlDbType.Float)
command.Parameters.Add("#Location", SqlDbType.VarChar)
command.Parameters.Add("#Date", SqlDbType.DateTime)

SQL Connection error 40 000webhost with Visual Basic

I am pretty sure I have all of my information right here, but I keep getting this error
http://puu.sh/qoZDQ/7294d6e682.png
The code I used: (Not mine)
I have the right username password and database name (I think)
'SET THE CONNECTION BETWEEN VISUAL BASIC AND MYSQL DATABASE
Dim con As SqlConnection = New SqlConnection("Data Source=mysql9.000webhost.com;" & "Initial Catalog=databasename;" & "User ID=username;" & "Password=password;")
'A SET OF COMMAND IN MYSQL
Dim cmd As New SqlCommand
'SET A CLASS THAT SERVES AS THE BRIDGE BETWEEN A DATASET AND DATABASE FOR SAVING AND RETRIEVING DATA.
Dim da As New SqlDataAdapter
'SET A CLASS THAT CONSISTS SPECIFIC TABLE IN THE DATABASE
Dim dt As New DataTable
Dim sqlQuery As String
Dim result As Integer
Private Sub register(ByVal sqlQuery As String)
Try
'OPENING THE CONNECTION
con.Open()
'HOLDS THE DATA TO BE EXECUTED
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'EXECUTE THE DATA
Result = cmd.ExecuteNonQuery
'CHECKING IF THE DATA HAS BEEN EXECUTED OR NOT
If result > 0 Then
MsgBox("User has been registered.")
Else
MsgBox("Failed to register the user.")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub login(ByVal sqlQuery As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'FILLING THE DATA IN A SPECIFIC TABLE OF THE DATABASE
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
'DECLARING AN INTEGER TO SET THE MAXROWS OF THE TABLE
Dim maxrow As Integer = dt.Rows.Count
'CHECKING IF THE DATA IS EXIST IN THE ROW OF THE TABLE
If maxrow > 0 Then
MsgBox("Welcome " & dt.Rows(0).Item(4))
Else
MsgBox("Account does not exist.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
Private Sub btn_Register_Click(sender As Object, e As EventArgs) Handles btn_Register.Click
sqlQuery = "INSERT INTO `dbuser` ( `user_name`, `user_username`, `user_pass`, `user_type`, `user_steamid`)" & "VALUES ('" & txtname.Text & "','" & txtusername.Text & "','" & txtpassword.Text & "','" & cbotype.Text & "','" & txtsteamid.Text & "')"
register(sqlQuery)
End Sub
Private Sub btn_Login_Click(sender As Object, e As EventArgs) Handles btn_Login.Click
sqlQuery = "SELECT * FROM `dbuser` WHERE user_username ='" & txtusername.Text & "' AND user_pass = '" & txtpassword.Text & "'"
login(sqlQuery)
End Sub
I used the database info from here http://puu.sh/qoZXo/a391cba854.jpg (Also not my info just an example so I dont post my info publicly)
I fixed my issue with the help of what Plutonix commented
MySql is not the same thing as Microsoft SqlServer – Plutonix
So I did some googling and found this: https://dev.mysql.com/downloads/connector/net/
This is the .Net framework for MySql (I think thats the right terms)
anyhow installing this then changing the top line of my code from
imports System.Data.SqlClient
To:
imports MySql.Data.MySqlClient
and changing the sql variables in the code to MySql variables by just adding My to the first bit, and it seems to work "better" I now have a new issue, but its with 000webhosts mysql database, not the code.

VB.net not working with SQL

I have a problem that is eating my brains out.
I have a project with 2 forms : 1 that extracts the data from my database ( name and surname) and another one that checks out if the user input of the user is correct (matching name and surname) . The code for the 1'st form is :
http://pastebin.com/rg5GMuu6
The code for the second is pasted here
I have no idea whatsoever how to repair this error. I've heard something about some sort of an adapter or something......Help
Ty in advance
I am using MySQL (Easy PHP);
Uploading some pics:
The first form is working without any problems, the second one gives me this error
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class Form2
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
'just a message
MsgBox(" You are searching for the users: " & vbCrLf & "Name: " & TextBox1.Text & vbCrLf & "Surname: " & TextBox2.Text)
' connecting to the database
dbCon = New MySqlConnection("Server = localhost; Database = users; Uid = root; Pwd = password")
strQuery = "SELECT users.name, users.surname FROM users" & _
" WHERE users.name = #Username AND users.surname = #UserPassword"
SQLCmd = New MySqlCommand(strQuery, dbCon)
SQLCmd.Parameters.AddWithValue("#Username ", TextBox1.Text)
SQLCmd.Parameters.AddWithValue("#UserPassword", TextBox2.Text)
'Database open
dbCon.Open()
DR = SQLCmd.ExecuteReader
If DR.HasRows = 0 Then
MsgBox("Not a match", MsgBoxStyle.Critical)
Else
MsgBox("You guessed the correct name: " & TextBox1.Text & "and the surname: " & TextBox2.Text)
End If
'Close
DR.Close()
dbCon.Close()
Catch ex As Exception
MsgBox("Failure to communicate " & vbCrLf & vbCrLf & ex.Message)
End Try
End Sub
End Class
Captured all the errors with the debugger
There seems to be odd situations with the .AddWithValue statement. I have found it better to set parameter values with the following two lines of code.
cmd.Parameters.Add(New SqlParameter("#UserName", Data.SqlDbType.NVarChar)).Direction = ParameterDirection.Input
cmd.Parameters("#UserName").Value = textbox1.text'obviously don't need this if it is an Output Param

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.