Visual Basic 2010 and Mysql Nested Query - mysql

I'm using VB2010 Express, I've got a Mysql tablet with the following Fields Ext, CostAssing and CostAct, I'm trying to update a Mysql table from the result got in a first query:
First query Get Ext and CostAssing
Second Query Update field CostAct with CostAssing value
**
Imports MySql.Data.MySqlClient
Imports System
Imports System.IO
Public Class Form1
Public dbconn As New MySqlConnection
Public sql As String
Public sqlQuery As String
Public SQLcmd As MySqlCommand
Public dbcomm As MySqlCommand
Public dbread As MySqlDataReader
Dim Ext As String
Dim CostAssing As Integer
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
dbconn = New MySqlConnection("Data Source=localhost ; user id=root ; password=password ; database=calls")
'First Query Get Extension and CostAssing
Try
dbconn.Open()
sqlQuery = "SELECT Ext,CostAssing FROM estruc "
SQLcmd = New MySqlCommand(sqlQuery, dbconn)
dbread = SQLcmd.ExecuteReader
While dbread.Read()
Ext = dbread.Item("Ext")
CostAssing = dbread.Item("CostAssing")
MsgBox("Ext:" & Ext)
'Second Query Update Ext from CostAct to CostAssing
Try
sqlQuery = "UPDATE estruc SET CostAct = '" & "1000" & "' WHERE Ext = '" & Ext & "'"
SQLcmd = New MySqlCommand(sqlQuery, dbconn)
dbread = SQLcmd.ExecuteReader
Catch ex As Exception
MsgBox("Error 2 is :" & ex.Message)
End Try
End While
Catch ex As Exception
MsgBox("Error 1 is :" & ex.Message)
End Try
dbread.Close()
End Sub
End Class
**
The first query run ok, I get fields Ext and CostAssing, But When the second Query try to Update de field CostAct I get following error (Reported by Catch ex As Exception MsgBox("Error 2 is :" & ex.Message)):
"Error 2 is: There is already an open Datareader associated with this Connection which must be closed first."
PLease, Any Ideas?

Add the following line to close the datareader after the first query
dbread.Close();
You'll want to store the values from dbread first (datatable or list, etc), close the while loop, then run the second query with:
SQLcmd.ExecuteNonQuery();
Please see this similar question

Related

My code was working earlier until I added error messages for checking if CapNum is empty or already existed on the database

Dim cmd As MySqlCommand
cmd = con.CreateCommand
con.Open()
Try
If String.IsNullOrEmpty(capNum.Text.ToString()) Then
MessageBox.Show("Please fill up the Capstone Number to proceed.")
Else
Dim theQuery As String = "select * from listofcapstone where caps_Number like '%" & capNum.Text & "%'"
Dim cmd1 As MySqlCommand = New MySqlCommand(theQuery, con)
Dim reader As MySqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
reader.Close()
MessageBox.Show("There's already an existing data with this Capstone Number!")
Else
cmd.CommandText = "insert into listofcapstone(caps_Number, thesis_Title, ictdu_entNumber, year, course)values(#caps_Number, #thesis_Title, #ictdu_entNumber, #year, #course)"
cmd.Parameters.AddWithValue("#caps_Number", capNum.Text)
cmd.Parameters.AddWithValue("#thesis_Title", title.Text)
cmd.Parameters.AddWithValue("#ictdu_entNumber", ictduCapNum.Text)
cmd.Parameters.AddWithValue("#year", yr.Text)
cmd.Parameters.AddWithValue("#course", course.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("SUCCESSFULLY ADDED!")
capNum.Clear()
title.Clear()
ictduCapNum.Clear()
course.Clear()
yr.SelectedIndex = -1
End If
End If
Catch ex As Exception
MessageBox.Show("Connection Lost!!")
Me.Close()
End Try
con.Close()
I found the problem on my code..i tried to remove try and catch to see which part of the code wasnt used properly and receive the "MySqlException was unhandled" error message..then put a reader on the else part
Dim theQuery As String = "select * from listofcapstone where caps_Number like '%" & capNum.Text & "%'"
Dim cmd1 As MySqlCommand = New MySqlCommand(theQuery, con)
Dim reader As MySqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
reader.Close()
MessageBox.Show("There's already an existing data with this Capstone Number!")
Else
reader.Close() 'Where I put the reader.'
cmd.CommandText = "insert into listofcapstone(caps_Number, thesis_Title, ictdu_entNumber, year, course)values(#caps_Number, #thesis_Title, #ictdu_entNumber, #year, #course)"
cmd.Parameters.AddWithValue("#caps_Number", capNum.Text)
cmd.Parameters.AddWithValue("#thesis_Title", title.Text)
I suggest you use parameterized queries instead of concatenating your queries like you're doing with that SELECT statement in order to mitigate SQL Injection attacks. You can read this and this to learn more about it.
You can also use the Using statement that will dispose of any object that has implemented the IDisposable interface such as the MySqlConnection and MySqlCommand objects. From the documentation:
Sometimes your code requires an unmanaged resource, such as a file
handle, a COM wrapper, or a SQL connection. A Using block guarantees
the disposal of one or more such resources when your code is finished
with them. This makes them available for other code to use.
You can also break down into separate Sub routines the queries for retrieving a record and inserting a new one. I put together a basic example showing what I discussed:
Imports System
Imports System.Data
Imports MySql.Data
Imports MySql.Data.MySqlClient
Namespace MySqlCmdExample
Class Program
Private Shared Sub Main(args As String())
Dim dataProvider As New AlbumDataProvider()
Try
If dataProvider.AlbumExists("Album_Five") Then
Console.WriteLine("Album exists...")
Return
End If
Console.WriteLine("Adding new album...")
dataProvider.AddAlbum(3, "Album_Five")
Catch ex As MySqlException
Console.WriteLine([String].Format("Oops, an error occurred: {0}", ex.Message))
End Try
End Sub
End Class
Public Class AlbumDataProvider
Private connectionString As String = "server=localhost;user=<your_username>;database=stack_overflow;port=3306;password=<your_password>"
Public Sub New()
End Sub
Public Function AlbumExists(name As String) As Boolean
Dim found As Boolean = False
Using conn As New MySqlConnection(connectionString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim cmd As New MySqlCommand("SELECT * FROM Album WHERE `Name` = #albumName", conn)
cmd.Parameters.AddWithValue("#albumName", name)
Using reader As MySqlDataReader = cmd.ExecuteReader()
found = reader.HasRows
End Using
End Using
Return found
End Function
Public Sub AddAlbum(ownerId As Integer, name As String)
Using conn As New MySqlConnection(connectionString)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim cmd As New MySqlCommand("INSERT INTO Album(OwnerId, Name) VALUES(#ownerId, #albumName)", conn)
cmd.Parameters.AddWithValue("#ownerId", ownerId)
cmd.Parameters.AddWithValue("#albumName", name)
cmd.ExecuteNonQuery()
End Using
End Sub
End Class
End Namespace

Why won't my .net application accept the SQL Query via user input?

I'm currently writing a quick .net program that will allow users to query a Database
I've got it working to a point where it'll run SELECT statements that are hardcoded but when I get the "sql" variable to look at the contents in a text box (user input) it chucks up an error. This happens even when I copy and paste a SQL Query that works hardcoded into the user text box
This is my code:
Imports MySql.Data.MySqlClient
Public Class form_queueDepth
Public dbconn As New MySqlConnection
Public sql As String
Public dbread As MySqlDataReader
Public dbcomm As MySqlCommand
Private Sub form_queueDepth_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbconn = New MySqlConnection("Data Source=10.232.7.41;user id=Alex;password=abc;database=alexvb")
Try
dbconn.Open()
MsgBox("Succeed")
Catch ex As Exception
MsgBox("Unable to connect: " & ex.Message.ToString)
End Try
End Sub
Private Sub button_ExecuteQuery_Click(sender As Object, e As EventArgs) Handles button_ExecuteQuery.Click
sql = "SELECT * FROM depth_store WHERE ID < '10';"
dbcomm = New MySqlCommand(sql, dbconn)
MsgBox(sql)
Try
dbread = dbcomm.ExecuteReader()
While dbread.Read
listBox_QueryResults.Items.Add(dbread("Queue_Manager").ToString() & " | " & dbread("Queue").ToString() & " | " & dbread("DTime").ToString() & " " & dbread("QueueDepth").ToString())
End While
MsgBox("Success")
Catch ex As Exception
MsgBox("Error: " & ex.Message.ToString)
End Try
End Sub
End Class
SO the above code will work but the moment i change "sql = "SELECT * FROM depth_store WHERE ID < '10';" to "sql = (textBox_UserQuery).ToString" and then copy & paste the query It chucks up an error stating:
http://i66.tinypic.com/2pqnxmo.png
Any suggestions/help would be much appreciated - Let me know if any you require any other information
textBox_UserQuery is the name of an instance of a TextBox.
The ToString() method returns the name of the class
IE: System.Windows.Forms.TextBox.
If you want to use the content of a TextBox you need the property Text.
sql = textBox_UserQuery.Text
Said that, I hope that this 'program' is only for your internal use. If not you are giving away the capability to destroy an entire database. (DELETE FROM .....)

How do you perform a SUM query through visual basic?

I am trying to to add up the points a certain user has earned from a mysql database table
My code returns an error saying the syntax is incorrect, I can't figure out how to make it work>
Here is my code:
Imports MySql.Data.MySqlClient
Public Class Leaderboard
Dim MysqlConn As MySqlConnection
Dim COMMAND As MySqlCommand
Private Sub submitBtn_Click(sender As Object, e As EventArgs) Handles submitBtn.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server=localhost;userid=root;password=root99;database=database"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "select SUM(Points) * from database.progress where candidate_number_fk = '" & textbox_can.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = Command.ExecuteReader
MessageBox.Show("You have successfully submitted your score")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
My.Forms.Menu1.Show()
Me.Hide()
End Sub
End Class
This is incorrect SQL syntax:
select SUM(Points) *
from database.progress
where . . .
Presumably, you intend:
select SUM(Points) as sumpoints
from database.progress
where . . .
You can then pull the field from the result set by name.
Note: There may be other problems with your code. This only addresses the SQL query.

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

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()