Call a Stored Procedure to perform Count on an array - mysql

I am selecting a distinct user from IT_Cases_List and stored it in an arraystaff().
From this array, I will then call a Stored Procedure to count the no of cases attended by this user,(arraystaff(i)) and loop it until arraystaff.length-1
but the problem is that the count does not tally.
Sub getStaff(ByVal month As String)
If Not con.State = ConnectionState.Closed Then
con.Open()
End If
Dim s As String = "select distinct Attended_by from IT_Cases_List where month(Resolution_date) ='" & month & "' "
s = s & "And Year(Resolution_date) ='" & ddyear.SelectedValue & "' and Attended_by is not null "
cmd = New SqlCommand(s, con)
da = New SqlDataAdapter
ds = New DataSet
da.SelectCommand = cmd
da.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
staffcount = ds.Tables(0).Rows.Count
ReDim arrstaff(staffcount - 1)
For Me.i = 0 To staffcount - 1
arrstaff(i) = ds.Tables(0).Rows(i).Item("Attended_by")
Next
getCases()
End If
End Sub
Sub getCases()
If con.State = ConnectionState.Closed Then
con.Open()
End If
ReDim arrdata(arrstaff.Length - 1, 0)
For Me.i = 0 To arrstaff.Length - 1
cmd = New SqlCommand("get_cases", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#ename", SqlDbType.VarChar).Value = arrstaff(i)
cmd.Parameters.Add("#Yr", SqlDbType.VarChar).Value = ddyear.SelectedValue
cmd.Parameters.Add("month", SqlDbType.VarChar).Value = m
cmd.ExecuteNonQuery()
da = New SqlDataAdapter()
da.SelectCommand = cmd
ds = New DataSet
da.Fill(ds)
If Not IsDBNull(ds.Tables(0).Rows(i).Item("NoCase")) Then
arrdata(i, 0) = ds.Tables(0).Rows(i).Item("NoCase")
End If
Next
cmd = New SqlCommand("delete from cases_Temp", con)
cmd.ExecuteNonQuery()
con.Close()
End Sub
and this is my stored procedure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[get_cases](
#Ename varchar(100),
#Yr varchar(50),
#month varchar(30))
AS
BEGIN
declare #NoCase as int
select #NoCase=COUNT(*)
from IT_Cases_List
where Attended_by= #Ename and month(Resolution_date) =#month and
Year(Resolution_date)=#Yr and Attended_by is not null
insert into cases_temp(Ename,NoCase)
values(#Ename,#NoCase)
select * from cases_Temp
end
i don't know what have i done wrong.
any help will be much appreciated.
UPDATE
ok, i've called only once getcases but i'm still having the same problem.
this is what i get when i run the program:
if i get Count(*) from the database, the total no of cases i should be getting is 132, whereas the total of cases i get from the program is 157 (7+7+20+20+49+49+5)
if i run the query from sql, this is what i should be getting
i notice that the Count number gets duplicated (7,7,20,20,49,49,5) instead of (7,20,49,5,10,27,13)
can anybody tell me what have i done wrong?

You should have called getCases() only once because inside it has a loop for each staff (arraystaff). Another thing, can you provide us a little more info regarding the problem? eg. sample records, desired output so we can more help you :)
UPDATE 1
move the ds = New DataSet before the For Loop, and pass the Command Object to the DataAdapter Object.
Sub getCases()
If con.State = ConnectionState.Closed Then
con.Open()
End If
ReDim arrdata(arrstaff.Length - 1, 0)
ds = New DataSet
For Me.i = 0 To arrstaff.Length - 1
cmd = New SqlCommand("get_cases", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#ename", SqlDbType.VarChar).Value = arrstaff(i)
cmd.Parameters.Add("#Yr", SqlDbType.VarChar).Value = ddyear.SelectedValue
cmd.Parameters.Add("month", SqlDbType.VarChar).Value = m
da = New SqlDataAdapter(cmd)
da.Fill(ds)
If Not IsDBNull(ds.Tables(0).Rows(i).Item("NoCase")) Then
arrdata(i, 0) = ds.Tables(0).Rows(i).Item("NoCase")
End If
Next
cmd = New SqlCommand("delete from cases_Temp", con)
cmd.ExecuteNonQuery()
con.Close()
End Sub

Related

Get Result from mysql by vb.net

I'm making a tool to help a company with there staff holiday (staff holiday calculator)
I connected myself by vb and its connection to the database but I can't get any result
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New api()
Dim adapter As New MySqlDataAdapter()
Dim table As New DataTable()
Dim command As New MySqlCommand("SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'", conn.getConnection())
command.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Try
conn.getConnection.Open()
adapter.SelectCommand = command
adapter.Fill(table)
Dim sqlReader As MySqlDataReader = command.ExecuteReader()
While sqlReader.Read()
namee = sqlReader("Full_Name").ToString()
job = sqlReader("Job").ToString()
days = sqlReader("Free_Days").ToString()
MsgBox(sqlReader("Full_Name").ToString())
End While
Label2.Text = "Name : " + namee
Label3.Text = "Job : " + job
Label8.Text = "Holiday Free Days : " & days
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End Try
End Sub
I didn't get any MsgBox and there is no error and the label text didn't change
I don't have MySQL, but based on MSSQL try something like this:
Dim namee, job, days As String
Dim commandText As String = "SELECT `Full_Name`, `Job`, `Free_Days` FROM `Holiday` WHERE `Username`= '#name'"
Dim conn As New api()
Using adapter As New MySqlDataAdapter(commandText, conn.getConnection())
adapter.SelectCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = api.id
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count = 0 Then
MessageBox.Show("No rows found", "ERROR")
Else
With table(0)
namee = .Item("Full_Name")
job = .Item("Job")
days = .Item("Free_Days")
End With
End If
End Using

Mysql ODBC Select command with parameter - not working

please, can anybody explain why this code is not working?
Connection to mysql is made via mysql odbc driver (latest).
Parameter in Select command is not recognized.
I also tried to replace #param1 in Select command:
Select product_id from product where model = ?
code still not working.
Sub Main()
Dim DBCONT As New Odbc.OdbcConnection
Dim strConn As String = "DSN=MyDSN"
DBCONT.ConnectionString = strConn
DBCONT.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model = #param"
.Connection = DBCONT
End With
Dim param1 As Odbc.OdbcParameter
param1 = cmd.CreateParameter()
With param1
.ParameterName = "#param"
.OdbcType = Odbc.OdbcType.VarChar
.Size = 30
.Value = "TESTVALUE"
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
Console.WriteLine(cmd.CommandText.ToString)
'this line displays "Select product_id from products where model = #param"
'instead of "Select product_id from products where model = "TESTVALUE"..
'WHY??
While reader.Read
Console.WriteLine(reader(0))
Console.WriteLine()
End While
Console.ReadLine()
DBCONT.Close()
reader = Nothing
cmd = Nothing
End Sub
Where it says:
".CommandText = "SELECT product_id FROM products WHERE model = #param"
Change it to:
".CommandText = "SELECT product_id FROM products WHERE model = '#param'"
(I've put ' ' around the #param, keep in mind this is different to the " " that is surrounding this)
I'm not 100% sure but I'll post this as an answer anyway because I think it's correct:
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model = :param"
.Connection = DBCONT
End With
Dim param1 As Odbc.OdbcParameter
param1 = cmd.CreateParameter()
With param1
.ParameterName = "param"
.OdbcType = Odbc.OdbcType.VarChar
.Size = 30
.Value = "TESTVALUE"
End With
Thanks for your help. This code is already working:
Sub Main()
Dim DBCONT As New Odbc.OdbcConnection
Dim strConn As String = "DSN=MyDSN"
DBCONT.ConnectionString = strConn
DBCONT.Open()
Dim cmd As New Odbc.OdbcCommand
With cmd
.CommandText = "SELECT product_id FROM products WHERE model LIKE ?"
//it seems it is important to add paramater right after commandtext
.Parameters.Add("#param", OdbcType.VarChar).Value = "%" + "TESTVALUE" + "%"
.Connection = DBCONT
End With
Dim reader As Odbc.OdbcDataReader
reader = cmd.ExecuteReader
Console.WriteLine(cmd.CommandText.ToString)
//it should display SELECT product_id FROM products WHERE model LIKE ?
While reader.Read
Console.WriteLine(reader(0))
Console.WriteLine()
End While
Console.ReadLine()
DBCONT.Close()
reader = Nothing
cmd = Nothing
End Sub

Vb.Net how to add another query to table?

Initially, I had one query that I converted it to PDF report (tables). However, now I would like to add another query in the table.
So that I have one query in a column.
My report have 3 columns and this query should be in third column as the first query will return two values id and name.
The second query I did was about calculating something.
Currently my code is like this:
Dim dr As SqlDataReader
command.CommandText = query
command.CommandType = CommandType.Text
command.Connection = con
con.Open()
dr = command.ExecuteReader()
Dim counter = 0
While dr.Read
Dim row As Row = table.AddRow()
row.Format.Alignment = ParagraphAlignment.Center
If counter Mod 2 = 0 Then
row.Shading.Color = TableRowA
Else
row.Shading.Color = TableRowB
End If
counter += 1
row.Cells(0).AddParagraph(counter)
row.Cells(0).Format.Alignment = ParagraphAlignment.Left
row.Cells(0).VerticalAlignment = VerticalAlignment.Bottom
row.Cells(1).AddParagraph(dr.GetString(1))
row.Cells(1).Format.Alignment = ParagraphAlignment.Left
row.Cells(2).AddParagraph(dr.GetInt32(0))
row.Cells(2).Format.Alignment = ParagraphAlignment.Left
row.Cells(3).AddParagraph("")
row.Cells(3).Format.Alignment = ParagraphAlignment.Left
End While
Can you show me how to alter this code to add the other query I have in last column?
Do I have to do While loop again? do I have to have another dr?
What I did is:
Dim drquery2 As SqlDataReader
Dim dr As SqlDataReader
command.CommandText = query
command.CommandType = CommandType.Text
command.Connection = con
con.Open()
dr = command.ExecuteReader()
command.CommandText = query2
command.CommandType = CommandType.Text
command.Connection = con
con.Open()
drquery2 = command.ExecuteReader()
Dim counter = 0
While dr.Read
Dim row As Row = table.AddRow()
row.Format.Alignment = ParagraphAlignment.Center
If counter Mod 2 = 0 Then
row.Shading.Color = TableRowA
Else
row.Shading.Color = TableRowB
End If
counter += 1
row.Cells(0).AddParagraph(counter)
row.Cells(0).Format.Alignment = ParagraphAlignment.Left
row.Cells(0).VerticalAlignment = VerticalAlignment.Bottom
row.Cells(1).AddParagraph(dr.GetString(1))
row.Cells(1).Format.Alignment = ParagraphAlignment.Left
row.Cells(2).AddParagraph(dr.GetInt32(0))
row.Cells(2).Format.Alignment = ParagraphAlignment.Left
row.Cells(3).AddParagraph(drquery2.GetInt32(0))
row.Cells(3).Format.Alignment = ParagraphAlignment.Left
End While
Is it correct?
Have you tried a Do...Until loop instead of While? Then try to use the counter as a Do Until counter = 3 (or maybe 4. It's been a while since I've done anything like this)

Visual Basic and Mysql in phpMyadmin [duplicate]

I'm working on my project which displays a list of employee. here, the information and picture of the employee will be shown. my project can now show the list of employees in the listbox and when I double click on an employee, his/her profile will be shown on a textbox. my problem is that i can't make their pictures to show in the picturebox. I already stored their picture on a table in my database along with their id, name, and profile. It only shows the picture of the first employee on the table. can anybody help me?
here's what I already done:
I populated the listbox:
Call Connect()
With Me
STRSQL = "Select employee_name from Employees"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
reader.Close()
adptr.SelectCommand = myCmd
adptr.Fill(dt)
lstEmployee.DisplayMember = "employee_name"
lstEmployee.ValueMember = "employee_id"
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
lstEmployee.Items.Add(dt.Rows(i)("employee_name"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
here's how I show the info on textbox
Dim FileSize As UInt32
Dim mStream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mStream.GetBuffer()
FileSize = mStream.Length
Dim cmd As New MySqlCommandBuilder
Call Connect()
With Me
STRSQL = "select employee_name, profile from Employees where employee_id = " & lstEmployee.SelectedIndex
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
txtName.Text = reader("employee_name")
txtProfile.Text = reader("profile")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
adptr.SelectCommand = myCmd
dt = New DataTable
adptr = New MySqlDataAdapter("select picture from Employees", myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
You miss the where clause is must be like to search a one employee to view there image.
adptr = _
New MySqlDataAdapter("select picture from Employees " + _
"where employee_id = " & lstEmployee.SelectedIndex, myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
P.S.: You must study the LINQ (Language-Integrated Query) for better approach.

Multiple Connection MYSQL VB.NET RowCount

I Have stack Here and does not go
I have a loop that makes connection to database but last 2 days have problem with counting row number. And nowere to find Solution
Dim row as Integer
For i = 100 To 120
Dim DBconn As MySql.Data.MySqlClient.MySqlConnection = New MySql.Data.MySqlClient.MySqlConnection(My.Settings.DBConnStr)
Dim da As MySql.Data.MySqlClient.MySqlDataAdapter
Dim dt As New DataTable
Dim sqlcmd As New MySql.Data.MySqlClient.MySqlCommand
sql = "SELECT Sum(D), Sum(P) FROM fin WHERE K like '" & i.ToString & "%' "
DBconn.Open()
da = New MySql.Data.MySqlClient.MySqlDataAdapter(sql, DBconn)
da.Fill(dt)
DBconn.Close()
row = dt.Rows.Count
MsgBox("i=" & i & " rows=" & row)
dt.Clear()
Next
MSG Box Alway tells me that the RowCount is 1, when manualy i make the query to MYSQL Diferent i Gives me Diferent Rows.
I am sure how you were able to get the dataadapter to fill a datatable. It should be filling a dataset. It should be
DIM ds as New Dataset()
da = New MySql.Data.MySqlClient.MySqlDataAdapter(sql, DBconn)
da.Fill(ds)
DIM rowCount = ds.Table(0).Rows.Count
Try this
DIM rowCount = ds.Tables(0).Select().Count