reading and comparing data values in MySQL database in vb.net - mysql

I'm trying to collect input from the user, check it against my database, and see if it exists in the database. If it does the program is supposed to fetch the last name, first name, and fees of the respective individual and output it.
Code:
Imports Mysql.Data.MySqlClient
Public Class Form1
Dim reader As MySqlDataReader
Dim command As New MySqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myConnectionString As String
myConnectionString = "server=localhost;" _
& "uid=root;" _
& "pwd=Emma#21*GCTU;" _
& "database=dummystudents"
Try
Dim conn As New MySql.Data.MySqlClient.MySqlConnection(myConnectionString)
conn.Open()
Dim sql As String = "SELECT idstudents FROM students WHERE idstudents = #TextBox1.Text "
command = New MySqlCommand(sql, conn)
reader = command.ExecuteReader()
If reader.Read() Then
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
End If
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
End Try
End Sub
End Class

Here's your SQL code:
SELECT idstudents FROM students WHERE idstudents = #TextBox1.Text
What's the point of pulling idstudents out when that's the value you're putting in? Worse, though, that's ALL you're pulling out, then you do this:
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
which would require you to pull back at least four columns.
The modification mentioned in the comments may well get your code to execute but it's not the right way to go. It looks like you tried to use a parameter but failed. Do that but do it right, i.e.
Dim sql As String = "SELECT idstudents, otherColumnsHere FROM students WHERE idstudents = #idstudents"
Using connection As New MySqlConnection(myConnectionString),
command As New MySqlCommand(sql, connection)
command.Parameters.Add("#idstudents", MySqlDbType.Int32).Value = CInt(TextBox1.Text)
conn.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
TextBox2.Text = reader(1)
TextBox3.Text = reader(2)
TextBox4.Text = reader(3)
End If
End Using
End Using

Related

There is already an open Data Reader associated with this connection which must be closed first vb.net.vb

Dim Conn As MySqlConnection
Dim Command As MySqlCommand
Dim Reader As MySqlDataReader
Dim server As String = "serverxxxxxxxx.1;user=root;database=xxxxxxxxx"
Public Sub testing()
Conn = New MySqlConnection
Conn.ConnectionString = server
Dim datecompare As String = Date.Today.ToString("yyyy-MM-dd hh:mm:ss")
Dim primarykey1 As String = ""
Dim primarykey2 As String = ""
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim Query1 As String
Query1 = "Select * From `tblborrow` Where `DueDate` = '" & datecompare & "'"
Command = New MySqlCommand(Query1, Conn)
Reader = Command.ExecuteReader
While Reader.Read
primarykey1 = Reader.GetInt32("BorrowID")
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim query2 As String
query2 = "Update `tblborrow` Set `Remarks` = '" & "Due Date" & "' Where `BorrowID` = '" & primarykey1 & "'"
Command = New MySqlCommand(query2, Conn)
Reader = Command.ExecuteReader
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'end of duedate
End While
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'for OVER DUE
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim Query1 As String
Query1 = "Select * From `tblborrow` Where `DueDate` < '" & datecompare & "'"
Command = New MySqlCommand(Query1, Conn)
Reader = Command.ExecuteReader
While Reader.Read
primarykey2 = Reader.GetInt32("BorrowID")
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim query2 As String
query2 = "Update `tblborrow` Set `Remarks` = '" & "Over Due" & "' Where `BorrowID` = '" & primarykey2 & "'"
Command = New MySqlCommand(query2, Conn)
Reader = Command.ExecuteReader
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'end of Over Due
End While
Reader.Close()
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call testing()
End Sub
I created a public sub that will select and update the Remarks in my database based on the borrowID(this is auto increment). The save date in DueDate and compare i declare with the current time today, but every time i click the button where i saved the code i get this error There is already an openDataReaderassociated with this connection which must be closed first
i double checked my code and didn't miss to put reader.close() after every conn.close() or i don't know maybe i missed..
i tried some several changes in my code but still i get the same error.
can some help me and build my code? .. thanks.
Try to use different variable for the readers, maybe Reader1 and Reader2.
It's probably because you used the same reader to execute different query hence the already open datareader error.
You try to open the same book which is already open. At least make it a different book.
You are attempting to open 2 readers on a single connection. See the double headed arrows.
Reader = Command.ExecuteReader'<<----
While Reader.Read
primarykey1 = Reader.GetInt32("BorrowID")
Try
If Not Conn.State = ConnectionState.Open Then
Conn.Open()
End If
Dim query2 As String
query2 = "Update `tblborrow` Set `Remarks` = '" & "Due Date" & "' Where `BorrowID` = '" & primarykey1 & "'"
Command = New MySqlCommand(query2, Conn)
Reader = Command.ExecuteReader '<<----
If you break your code into logical units with only a single thing happening in each method it is a bit easier to see where things go wrong.
Keeping your database objects local to the methods where they are used allows you to be sure they are closed and disposed. Using...End Using blocks handle this for you even if there is an error.
Notice, in the 2 Update methods, the parameters are added outside the For loop and only the value that changes is set inside the loop.
Dim ConString As String = "serverxxxxxxxx.1;user=root;database=xxxxxxxxx"
Public Sub GetPKs()
Dim pkList As New List(Of Integer)
Dim DueDate As String = Date.Today.ToString("yyyy-MM-dd hh:mm:ss")
Using Conn As New MySqlConnection(ConString),
cmd As New MySqlCommand("Select BorrowID From tblborrow Where DueDate = #DueDate")
cmd.Parameters.Add("#DueDate", MySqlDbType.VarChar, 100).Value = DueDate
Conn.Open()
Using reader As MySqlDataReader = cmd.ExecuteReader
While reader.Read
pkList.Add(reader.GetInt32("BorrowID"))
End While
End Using
End Using
UpdateRemarks(pkList, DueDate)
End Sub
Private Sub UpdateRemarks(pks As List(Of Integer), DueDate As String)
Using con As New MySqlConnection(ConString),
cmd As New MySqlCommand("Update tblborrow Set Remarks = #DueDate Where BorrowID = #PK", con)
With cmd.Parameters
.Add("#DueDate", MySqlDbType.VarChar, 100).Value = DueDate
.Add("#PK", MySqlDbType.Int32)
End With
con.Open()
For Each i In pks
cmd.Parameters("#PK").Value = i
cmd.ExecuteNonQuery()
Next
End Using
End Sub
Private Sub GetOverduePKs()
Dim pkList As New List(Of Integer)
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("Select BorrowID From tblborrow Where DueDate < #DueDate")
cmd.Parameters.Add("#DueDate", MySqlDbType.VarChar, 100).Value = Date.Today.ToString("yyyy-MM-dd hh:mm:ss")
cn.Open()
Using reader = cmd.ExecuteReader
While reader.Read
pkList.Add(reader.GetInt32("BorrowID"))
End While
End Using
End Using
UpdateOverdueRemarks(pkList)
End Sub
Private Sub UpdateOverdueRemarks(pks As List(Of Integer))
Using cn As New MySqlConnection(ConString),
cmd As New MySqlCommand("Update tblborrow Set Remarks = 'Over Due' Where BorrowID = #PK")
cmd.Parameters.Add("#PK", MySqlDbType.Int32)
cn.Open()
For Each i In pks
cmd.Parameters("#PK").Value = i
cmd.ExecuteNonQuery()
Next
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
GetPKs()
GetOverduePKs()
End Sub
use 2 connections CONN and CONN2, with the same parameters, use CONN to open the QUERY1 reader. While reading, use CONN2 to create the 2nd query. Note that this works for MySQL. MS-Access can handle multiple commands in one connection, MySql cannot and needs separate connections. Sqlite cannot handle 2 simultanuos connections. there you have to use in incore temporary array or list. From a working program:
Dim DbConn As New MySqlConnection(SqlProv)
Dim DbConn2 As New MySqlConnection(SqlProv)
-
Dim SQLsfSelect As String = "SELECT CollSeq FROM ToBeIndexed WHERE CollCode = #CollCode"
Dim DRsfSelect As MySqlDataReader = Nothing
Dim DCsfSelect As MySqlCommand
Dim sfSelP1 As New MySqlParameter("#CollCode", MySqlDbType.VarChar, 4)
DCsfSelect = New MySqlCommand(SQLsfSelect, DbConn)
-
Dim SQLasSelect As String = "SELECT DISTINCT CollSeq FROM Data WHERE CollCode = #CollCode ORDER BY CollSeq"
Dim DRasSelect As MySqlDataReader = Nothing
Dim DCasSelect As MySqlCommand
Dim asSelP1 As New MySqlParameter("#CollCode", MySqlDbType.VarChar, 4)
DCasSelect = New MySqlCommand(SQLasSelect, DbConn2)
-
DbConn.Open()
sfSelP1.Value = CurCollCode
CollSeqToIdxC.Clear()
Try
DRsfSelect = DCsfSelect.ExecuteReader()
Do While (DRsfSelect.Read())
CollSeq = GetDbIntegerValue(DRsfSelect, 0)
DbConn2.Open()
asSelP1.Value = CurCollCode
Try
DRasSelect = DCasSelect.ExecuteReader()
Do While (DRasSelect.Read())
CollSeq = GetDbIntegerValue(DRasSelect, 0)
CollSeqToIdxC.Add(CollSeq, CStr(CollSeq))
Loop
Catch ex As Exception
MsgBox(ex.ToString(), , SysMsg1p(402, CurCollCode))
Finally
If Not (DRasSelect Is Nothing) Then
DRasSelect.Close()
End If
End Try
DbConn2.Close()
Loop
Catch ex As Exception
MsgBox(ex.ToString(), , SysMsg1p(403, CurCollCode))
Finally
If Not (DRsfSelect Is Nothing) Then
DRsfSelect.Close()
End If
End Try
DbConn.Close()

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

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.

button not working when i insert new data

when I input data are not yet available. button does not work
but when I enter existing data in the database, the button work for find existing records in the database and msgbox.appear
this my coding. (i am using Microsoft Visual Basic 2008 express edition database mysql)
Imports MySql.Data.MySqlClient
Public Class Form2
Public conn As MySqlConnection
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Application.DoEvents()
Button1.Focus()
conn = New MySqlConnection
'conn.ConnectionString = "server=localhost;database=ilmu;userid=root;password= ''"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show("Error1: " & ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn = New MySqlConnection("server=localhost;database=ilmu;userid=root;password= ''")
Try
conn.Open()
Dim sqlquery As String = "SELECT * FROM visitor WHERE nama = '" & TextBox1.Text & "';"
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() = True Then
If data(2).ToString = TextBox2.Text Then
command = New MySqlCommand
command.Connection = conn
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:tt")
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES ('" & TextBox1.Text & "','" & tkhupd & "')"
command.ExecuteNonQuery()
MessageBox.Show(" Berjaya, Sila Masuk. ", "Tahniah", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MsgBox("exist")
End If
Else
MsgBox("Failed Login.")
End If
End While
Catch ex As Exception
End Try
End Sub
End Class
I am not sure what you are trying to do when there is not matching record in the database, but you don't have any code that would be hit in the case of no matching entries.
If there are no matching records, your while condition isn't met and nothing in the loop happens.
Fixing it likely involves rearranging the order of your loop and your if condition.
Check to see if data.hasRows first.
Example:
If data.HasRows() = True Then
While Data.Read
//code here for found rows
End While
Else
//code for no matching entries
End If
And as has been mentioned in Joel's comment, you really should look at using parameterized queries.
example of your insert command altered:
command.CommandText = "INSERT INTO visitor(noK,khupd)VALUES (?noK,?khupd)"
command.Parameters.AddWithValue("?noK",TextBox1.Text)
command.Parameters.AddWithValue("?khupd", tkhupd)
command.ExecuteNonQuery()