How do you perform a SUM query through visual basic? - mysql

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.

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

Displaying data from different tables in MySql Database into vb.net 2012 Textboxes

am trying to run some lines of code to enable me display some data from different tables from MySql database in vb.net 2012. This is how it works. When i login with my username and password, it should display the name of my store and branch name in the text box provided using my login details. This code is not written in the login form. below is my code
Imports MySql.Data.MySqlClient
Public Class SelectionForm
Dim sqlconn As MySqlConnection
Dim sqlcmd As MySqlCommand
Private Sub SelectionForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
sqlconn = New MySqlConnection
sqlconn.ConnectionString = "server=localhost;userid=root;password=;database=osap"
Dim sqlreader As MySqlDataReader
'Dim sqladapter As MySqlDataAdapter
Try
sqlconn.Open()
Dim Query As String
Query = "SELECT sales_reps.username, stores.name, branches.name FROM sales_reps, stores, branches WHERE sales_reps.id =(SELECT id FROM sales_reps WHERE username='" & LoginForm.UserTextBox.Text & "' AND password='" & LoginForm.PassTextBox.Text & "') AND branches.id = sales_reps.branch_id AND stores.id = branches.store_id"
sqlcmd = New MySqlCommand(Query, sqlconn)
sqlreader = sqlcmd.ExecuteReader()
If sqlreader.HasRows Then
sqlreader.Read()
BranchTextBox.Text = sqlreader.GetString("branches.name")
StoreTextBox.Text = sqlreader.GetString("stores.name")
End If
sqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
sqlconn.Dispose()
End Try
End Sub
End Class
No errors are displayed but doesn't show the data in the text boxes either.

Sql Syntax Error at Line 1 using VB.net and Mysql server

I am getting an Sql syntax error check the manual that corresponds to your MySQL server version for the right syntax to user near line 1. I am trying to save to my database. I am using VB.net.
Imports MySql.Data.MySqlClient
Public Class AddStudent
Dim mydbcon As MySqlConnection
Dim COMMAND As MySqlCommand
Dim da As New MySqlDataAdapter
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=jared;password=jared;database=database"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "Insert into database.scitech (Name,Surname,Number,College,Course,Year) values ('" & TextBox1name.Text & "','" & TextBox2su.Text & "','" & TextBox3num.Text & "'"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader
MessageBox.Show("Data Saved")
mydbcon.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mydbcon.Dispose()
End Try
End Sub
End Class
Replacing your variables with literals it seems like you're missing a right parenthesis:
"Insert into database.scitech (Name,Surname,Number,College,Course,Year) values ('abc','def','ghi'"
Might be a good idea to output your query when debugging SQLs.

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

Visual Basic 2010 and Mysql Nested Query

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