I want to update the UsageTime when the time ticks per minute, couldn't get the right code.
Private Sub LBLTime_TextChanged(sender As Object, e As EventArgs) Handles LBLTime.TextChanged
con.ConnectionString = My.Settings.Finals_DBConnectionString
cmd.Connection = con
con.Close()
con.Open()
cmd.CommandText = "update tbl_transaction set usagetime = #ut, remainingtime = #rt"
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("ut", +1)
cmd.Parameters.AddWithValue("rt", -1)
cmd.Parameters cmd.ExecuteNonQuery()
End With
End Sub
try this.
update tbl_transaction set usagetime = usagetime+1 , remainingtime = remainingtime -1
Also don't see any "where" in your sql. It's not a good practice
Related
that's my first time here, I'm going mad because of this problem I have:
I'm developing a windows form application with VB.NET using multiple types of connections(mysql,odbc and SQL server) everything works fine until I get into MySQL..
MySQL server is a physical windows 7 pc, I connect to it through IPSEC VPN TUNNEL.
I need to perform 2 MySQL connections every x seconds, if I get some type of result after the first connection then I'll open the second one, and so on every x seconds(that's all wrote in my timer.tick event handler).
The problem is that quite often some connections on MySQL server keep staying alive(ESTABLISHED) on MySQL server and I can't find out why... code looks fine, there are both open and close methods declared at the right time, I've also tried Dispose,ClearPool and ClearAllPools methods but I keep having those connections up until I close my program or it reaches connection limit.
Here's the code:
Class connection:
Public Sub connMySQL()
Dim connstring As String
Try
If stabilimento = "1PR" Then
If cesoia = "" Then
connstring = "server=192.168.123.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Else
connstring = "server=192.168.123.253;userid=xx;password=xx;database=xx;Connect Timeout=30"
End If
End If
If stabilimento = "2PR" Then
If cesoia = "" Then
connstring = "server=192.168.1.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Else
connstring = "server=192.168.123.253;userid=root;password=xx;database=xx;Connect Timeout=30"
End If
End If
conMySql = New MySqlConnection(connstring)
If conMySql.State = ConnectionState.Closed Then
conMySql.Open()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Class where the iteration is performed:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
connMySQL()
comm = New MySqlCommand("SELECT count_1,count_2,start_stop,data_ora,id FROM plc_contatori where plc_nome='" + plc_nome + "' and data_ora > '" + data_ieri.ToString("yyyy/MM/dd") + "' order by data_ora desc limit 1", conMySql)
dr = comm.ExecuteReader()
While (dr.Read())
count_1(0) = dr.GetValue(0)
start_stop(0) = dr.GetValue(2)
data_ora(0) = dr.GetValue(3)
If id <> dr.GetValue(4) And count_2(0) <> dr.GetValue(1) Then
id = dr.GetValue(4)
count_2(0) = dr.GetValue(1)
Else
Exit Sub
End If
End While
dr.Close()
dr.Dispose()
conMySql.Close()
conMySql.Dispose()
conMySql.ClearPool(conMySql)
conMySql.ClearAllPools()
If Not conMySql Is Nothing Then conMySql = Nothing
comm.Dispose()
If start_stop(0) = 1 Then
Exit Sub
End If
Dim dum_count_2 As Integer = count_2(0) - 1
connMySQL()
comm = New MySqlCommand("select count_1,count_2,start_stop,data_ora from plc_contatori where plc_nome='" + plc_nome + "' and data_ora > '" + data_ieri.ToString("yyyy/MM/dd") + "' AND count_2=" + dum_count_2.ToString + " ORDER BY data_ora desc limit 1", conMySql)
dr = comm.ExecuteReader()
While (dr.Read())
count_1(1) = dr.GetValue(0)
count_2(1) = dr.GetValue(1)
start_stop(1) = dr.GetValue(2)
data_ora(1) = dr.GetValue(3)
End While
dr.Close()
dr.Dispose()
conMySql.Close()
conMySql.Dispose()
conMySql.ClearPool(conMySql)
conMySql.ClearAllPools()
If Not conMySql Is Nothing Then conMySql = Nothing
comm.Dispose()
If count_1(0) = count_1(1) And start_stop(1) <> 1 And count_2(0) <> count_2(1) Then
'sub that reads some values from an odbc connection
CheckFermo()
End If
End Sub
NOTE that variables that I have not declared in this portion of code are declared in the public class of the form.
I'm wondering what could be wrong... maybe the 2nd connection is being established before the 1st one gets closed by the server?
I changed the connMySQL method to a function that returns the connection string. I have declared several variables so the code makes sense. I made several assumptions about datatypes. You may have to change this back to String and VarChar if these values are actually stored as strings. (I hope they are not)
You could use a single connection but all the assignments and comparisons would occur with an open connection.
Private stabilimento As String
Private cesoia As String
Public Function connMySQL() As String
Dim connstring As String
Select Case True
Case stabilimento = "1PR" And cesoia = ""
connstring = "server=192.168.123.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Case stabilimento = "2PR" And cesoia = ""
connstring = "server=192.168.1.18;userid=xx;password=xx;database=xx;Connect Timeout=30"
Case Else
connstring = "server=192.168.123.253;userid=root;password=xx;database=xx;Connect Timeout=30"
End Select
Return connstring
End Function
Private count_1(10) As Integer
Private count_2(10) As Integer
Private start_stop(10) As Integer
Private data_ora(10) As Date
Private id As Integer
Private plc_nome As String
Private data_ieri As Date
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Using dt As New DataTable
Using cn As New MySqlConnection(connMySQL),
comm = New MySqlCommand("SELECT count_1,count_2,start_stop,data_ora,id
FROM plc_contatori
where plc_nome= #plcNome and data_ora > #dataOra
order by data_ora desc
limit 1", cn)
comm.Parameters.Add("plcNome", MySqlDbType.VarChar).Value = plc_nome
comm.Parameters.Add("dataOra", MySqlDbType.Date).Value = data_ieri '.ToString("yyyy/MM/dd")
cn.Open()
Using dr = comm.ExecuteReader
dt.Load(dr)
End Using 'closes and disposes reader
End Using 'closes and dispose connection and command
count_1(0) = CInt(dt(0)(0))
start_stop(0) = CInt(dt(0)(2))
data_ora(0) = CDate(dt(0)(3))
If id <> CInt(dt(0)(4)) AndAlso count_2(0) <> CInt(dt(0)(1)) Then
id = CInt(dt(0)(4))
count_2(0) = CInt(dt(0)(1))
Else
Exit Sub
End If
End Using 'disposes DataTable
If start_stop(0) = 1 Then
Exit Sub
End If
Dim dum_count_2 As Integer = count_2(0) - 1
Using dt As New DataTable
Using cn As New MySqlConnection(connMySQL),
comm As New MySqlCommand("select count_1,count_2,start_stop,data_ora
from plc_contatori
where plc_nome= #plcNome
and data_ora > #dataOra
AND count_2= #count2
ORDER BY data_ora desc
limit 1", cn)
comm.Parameters.Add("#plcNome", MySqlDbType.VarChar).Value = plc_nome
comm.Parameters.Add("#dataOra", MySqlDbType.Date).Value = data_ieri '.ToString("yyyy/MM/dd")
comm.Parameters.Add("#count2", MySqlDbType.Int32).Value = dum_count_2 '.ToString
cn.Open()
Using dr = comm.ExecuteReader()
dt.Load(dr)
End Using
End Using
count_1(1) = CInt(dt(0)(0))
count_2(1) = CInt(dt(0)(1))
start_stop(1) = CInt(dt(0)(2))
data_ora(1) = CDate(dt(0)(3))
End Using
If count_1(0) = count_1(1) AndAlso start_stop(1) <> 1 AndAlso count_2(0) <> count_2(1) Then
'sub that reads some values from an odbc connection
CheckFermo()
End If
End Sub
I am making a voting system in visual basic, I'm struggling to write the right query for identifying the max vote count and also showing the the same vote count, what I mean is the draw in the candidates, how can I identify if there are draws in the election... here is my code
Private Sub president()
Dim cmd1 As New MySqlCommand("SELECT MAX(VOTECOUNT) as MV FROM candidates WHERE POSITION = 'PRESIDENT'", con)
Dim rd1 As MySqlDataReader
con.Open()
rd1 = cmd1.ExecuteReader()
If rd1.Read() Then
MV = rd1("MV").ToString
End If
con.Close()
rd1.Dispose()
Dim cmd As New MySqlCommand("SELECT CONCAT(FIRSTNAME,' ',MIDDLENAME,' ',LASTNAME) AS FULLNAME,POSITION, VOTECOUNT FROM candidates WHERE POSITION = 'PRESIDENT' AND VOTECOUNT = '" & MV & "'", con)
Dim rd As MySqlDataReader
con.Open()
rd = cmd.ExecuteReader()
While rd.Read()
TextBox1.Text = (rd("FULLNAME"))
End While
rd.Close()
con.Close()
Using...End Using blocks ensure that your database objects are closed and disposed. You can use .ExecuteScalar to get a single value from the database. This returns an Object so a CInt is needed. I think one of your problems was that you were surrounding MV in single quotes in the second Select statement. I am sure that this is an Integer and you were passing it as a string. Using parameters solves this problem.
Private Sub president()
Using con As New MySqlConnection(ConStr),
cmd1 As New MySqlCommand("SELECT MAX(VOTECOUNT) as MV FROM candidates WHERE POSITION = 'PRESIDENT'", con)
con.Open()
Dim MV = CInt(cmd1.ExecuteScalar())
cmd1.CommandText = "SELECT CONCAT(FIRSTNAME,' ',MIDDLENAME,' ',LASTNAME) AS FULLNAME,POSITION, VOTECOUNT FROM candidates WHERE POSITION = 'PRESIDENT' AND VOTECOUNT = #MV"
cmd1.Parameters.Add("#MV", MySqlDbType.Int32).Value = MV
Using rd = cmd1.ExecuteReader()
While rd.Read()
TextBox1.AppendText(rd("FULLNAME").ToString & vbCrLf)
End While
End Using
End Using
End Sub
I tried so many things but nothing fixes it, as any of the INSERT Command or DELETE Command in MySQL Database are working fine, only UPDATE Command swaps the first and second column unnecessarily, when it's displayed using the SELECT Command.
So, I need to close my app. and then re-Run it, then the columns are then displayed correctly, only until I execute UPDATE Command again, which messes with the first and second column.
Any idea why this is happening!
Here is my code
Sub DB_CMD_FUNC(SENDER As String)
'Database realted script
Dim con As New MySqlConnection("server=localhost; user=root; password=****; database=****;")
Dim cmd As New MySqlCommand
Dim dt As New DataTable
Dim da As New MySqlDataAdapter
Dim sql As String
Dim DR As MySqlDataReader
Dim SQL_CMD_TXT = "UPDATE `employees` SET `NAME`= '" & EMPLOYEE_EDIT_FRM.EDIT_NAME_TXT.Text & "', _
`FATHER_NAME`='" & EMPLOYEE_EDIT_FRM.EDIT_FATHER_NAME_TXT.Text & "', `DOB`='" &
EMPLOYEE_EDIT_FRM.EDIT_DOB_TXT.Text & "',`DOJ`='" &
EMPLOYEE_EDIT_FRM.EDIT_DOJ_TXT.Text & "',`POSITION`='" &
EMPLOYEE_EDIT_FRM.EDIT_POSITION_TXT.Text &
"',`EMP_STATUS`='" & EMPLOYEE_EDIT_FRM.EDIT_EMP_STATUS_TXT.Text & "', _
`SALARY`='" & EMPLOYEE_EDIT_FRM.EDIT_SALARY_TXT.Text & "',`EOS`='" &
EMPLOYEE_EDIT_FRM.EDIT_EOS_TXT.Text & "', _
`MOBILE`='" & EMPLOYEE_EDIT_FRM.EDIT_REMARKS_TXT.Text & "' WHERE
`EMPLOYEE_ID` = '" & EMPLOYEE_EDIT_FRM.EDIT_ID_TXT.Text & "';
Select `NAME` FROM `employees` WHERE
`EMPLOYEE_ID`='" & EMPLOYEE_EDIT_FRM.EDIT_ID_TXT.Text & "';"
Try
'DB CMD EXECUTION
con.Open()
With cmd
sql = SQL_CMD_TXT
.Connection = con
.CommandText = sql
End With
dt.Clear()
da.SelectCommand = cmd
da.Fill(dt)
'Command for datagridview object
With OBJECT_DATAGRIDVIEW
.DataSource = dt
'Scroll to the last row.
.Name = "MYDATAGRIDVIEW"
.FirstDisplayedScrollingRowIndex = .RowCount - 1
End With
con.Close()
Catch ex As Exception
MessageBox.Show("ERROR FOR SQL CMD EXECUTION SECTION-" & ex.Message,
"SQL CMD EXECUTION", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End Try
End Sub
Your UPDATE-query seems to be structurally fine. But please do use SQL parameters, because if you now include an apostrophe (') within your entered textbox values, the query will most likely crash. (Or worse: some malicious user might apply SQL injection to manipulate your database!)
But after the UPDATE-query, you execute a small SELECT query. This SELECT query returns only the NAME of only the updated record. This single row with a single column is captured in a DataTable object, and that DataTable object is set as the new data source for your DataGridView.
Is that your real intention? In your place, I would probably want to select all relevant fields from the database table and include all records, so that everything will be shown/refreshed in the DataGridView...
You probably already have some SELECT query in your application's startup code to initially fill the DataGridView. I would personally put that code in a separate subroutine (called something like FillDataGridView) and call that subroutine in the application's (or the form's) startup code and also call it after executing the UPDATE query. So there would not be any need to include a separate SELECT query after your UPDATE query.
You could check out the following code for some inspiration. Note that I haven't tested the code (because I do not have MySQL installed on my machine), so it might quite certainly require some additional tweaking and bugfixing inside your application's code.
Private Sub DB_CMD_FUNC(SENDER As String)
Dim SQL_CMD_TXT As New StringBuilder()
SQL_CMD_TXT.AppendLine("UPDATE `employees`")
SQL_CMD_TXT.AppendLine("SET")
SQL_CMD_TXT.AppendLine(" `NAME` = #name,")
SQL_CMD_TXT.AppendLine(" `FATHER_NAME` = #father_name,")
SQL_CMD_TXT.AppendLine(" `DOB` = #dob,")
SQL_CMD_TXT.AppendLine(" `DOJ` = #doj,")
SQL_CMD_TXT.AppendLine(" `POSITION` = #position,")
SQL_CMD_TXT.AppendLine(" `EMP_STATUS` = #status,")
SQL_CMD_TXT.AppendLine(" `SALARY` = #salary,")
SQL_CMD_TXT.AppendLine(" `EOS` = #eos,")
SQL_CMD_TXT.AppendLine(" `MOBILE` = #mobile'")
SQL_CMD_TXT.AppendLine("WHERE")
SQL_CMD_TXT.AppendLine(" `EMPLOYEE_ID` = #ID;")
Try
Dim ID As String = EMPLOYEE_EDIT_FRM.EDIT_ID_TXT.Text
If String.IsNullOrWhiteSpace(ID) Then
Throw New Exception("The ID is required.")
End If
Dim NAME As String = EMPLOYEE_EDIT_FRM.EDIT_NAME_TXT.Text
If String.IsNullOrWhiteSpace(NAME) Then
NAME = Nothing
End If
Dim FATHER_NAME As String = EMPLOYEE_EDIT_FRM.EDIT_FATHER_NAME_TXT.Text
If String.IsNullOrWhiteSpace(FATHER_NAME) Then
FATHER_NAME = Nothing
End If
Dim DD As Date
Dim DOB As Date?
Dim DOJ As Date?
If Date.TryParse(EMPLOYEE_EDIT_FRM.EDIT_DOB_TXT.Text, DD) Then
DOB = DD
Else
DOB = Nothing
End If
If Not Date.TryParse(EMPLOYEE_EDIT_FRM.EDIT_DOJ_TXT.Text, DD) Then
DOJ = DD
Else
DOJ = Nothing
End If
Dim POSITION As String = EMPLOYEE_EDIT_FRM.EDIT_POSITION_TXT.Text
If String.IsNullOrWhiteSpace(POSITION) Then
POSITION = Nothing
End If
Dim STATUS As String = EMPLOYEE_EDIT_FRM.EDIT_EMP_STATUS_TXT.Text
If String.IsNullOrWhiteSpace(STATUS) Then
STATUS = Nothing
End If
Dim DEC As Decimal
Dim SALARY As Decimal?
If Decimal.TryParse(EMPLOYEE_EDIT_FRM.EDIT_SALARY_TXT.Text, DEC) Then
SALARY = DEC
Else
SALARY = Nothing
End If
Dim EOS As Date?
If Date.TryParse(EMPLOYEE_EDIT_FRM.EDIT_EOS_TXT.Text, DD) Then
EOS = DD
Else
EOS = Nothing
End If
Dim MOBILE As String = EMPLOYEE_EDIT_FRM.EDIT_REMARKS_TXT.Text
If String.IsNullOrWhiteSpace(MOBILE) Then
MOBILE = Nothing
End If
Using con As New MySqlConnection("server=localhost; user=root; password=****; database=****;")
''Do not open the database connection just yet...
'con.Open()
Using cmd As New MySqlCommand(SQL_CMD_TXT.ToString(), con)
cmd.Parameters.Add("#id", MySqlDbType.VarChar).Value = ID
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = NAME
cmd.Parameters.Add("#father_name", MySqlDbType.VarChar).Value = FATHER_NAME
cmd.Parameters.Add("#dob", MySqlDbType.Date).Value = DOB
cmd.Parameters.Add("#doj", MySqlDbType.Date).Value = DOJ
cmd.Parameters.Add("#position", MySqlDbType.VarChar).Value = POSITION
cmd.Parameters.Add("#status", MySqlDbType.VarChar).Value = STATUS
cmd.Parameters.Add("#salary", MySqlDbType.Decimal).Value = SALARY
cmd.Parameters.Add("#eos", MySqlDbType.Date).Value = EOS
cmd.Parameters.Add("#mobile", MySqlDbType.VarChar).Value = MOBILE
con.Open() 'Delayed opening the database connection until the very last moment.
cmd.ExecuteNonQuery()
End Using
''Explicitly closing the database connection is not necessary, because the disposal (triggered when the Using-block is ended) takes care of that.
'con.Close()
End Using
Catch ex As Exception
MessageBox.Show($"ERROR FOR SQL CMD EXECUTION SECTION - {ex.Message}",
"SQL CMD EXECUTION",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
Exit Sub
End Try
FillDataGridView()
End Sub
Private Sub FillDataGridView()
Dim SQL_CMD_TXT As New StringBuilder()
SQL_CMD_TXT.AppendLine("SELECT")
SQL_CMD_TXT.AppendLine(" `ID`,")
SQL_CMD_TXT.AppendLine(" `NAME`,")
SQL_CMD_TXT.AppendLine(" `FATHER_NAME`,")
SQL_CMD_TXT.AppendLine(" `DOB`,")
SQL_CMD_TXT.AppendLine(" `DOJ`,")
SQL_CMD_TXT.AppendLine(" `POSITION`,")
SQL_CMD_TXT.AppendLine(" `EMP_STATUS`,")
SQL_CMD_TXT.AppendLine(" `SALARY`,")
SQL_CMD_TXT.AppendLine(" `EOS`,")
SQL_CMD_TXT.AppendLine(" `MOBILE`")
SQL_CMD_TXT.AppendLine("FROM")
SQL_CMD_TXT.AppendLine(" `employees`;")
Try
Dim dt As New DataTable()
Using con As New MySqlConnection("server=localhost; user=root; password=****; database=****;")
''Do not open the database connection just yet...
'con.Open()
Using cmd As New MySqlCommand(SQL_CMD_TXT.ToString(), con)
Using da As New MySqlDataAdapter(cmd)
con.Open() 'Delayed opening the database connection until the very last moment.
da.Fill(dt)
End Using
End Using
''Explicitly closing the database connection is not necessary, because the disposal (triggered when the Using-block is ended) takes care of that.
'con.Close()
End Using
With OBJECT_DATAGRIDVIEW
.DataSource = dt
.FirstDisplayedScrollingRowIndex = .RowCount - 1 'Scroll to the last row.
End With
Catch ex As Exception
MessageBox.Show($"ERROR FOR SQL CMD EXECUTION SECTION - {ex.Message}",
"SQL CMD EXECUTION",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
End Sub
I will explain this as much as possible.
I have a project which need to show the names from database to textboxes. I have 2 datetimepicker for searching between dates and 5 textboxes to show the names in mysql database. for example I select the from start date 2018/12/07 and end date 2019/01/07 in the datagridview it will show all the rows and columns in-between dates. However, I need the names to show on my 5 textboxes. I don't have a code since I don't know where to begin with.
In mysqldatabase I have only id,name,dateofentry.
In my form :
datetimepicker1 = startdate
datetimepicker2 = enddate
button1 = generatebutton
textbox1 = nametxt1
textbox2 = nametxt2
textbox3 = nametxt3
textbox4 = nametxt4
textbox5 = nametxt5
Update when I use this:
mysqlconn.Open()
COMMAND.Connection = mysqlconn
COMMAND.CommandText = "Select name from table1 where dateofentry between '" & Format(Me.startdate.Value, "yyyy-MM-dd") & "' AND '" & Format(Me.endtime.Value, "yyyy-MM-dd") & "'"
Dim sqlresult1 As Object
sqlresult1 = COMMAND.ExecuteScalar
Dim str1 As String
str1 = sqlresult1
nametxt1.Text = str1
mysqlconn.Close()
The same name shows in each of my 5 textboxes
Thank you for answering this question.
Explanations and comments in-line.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'The Using block ensures that your database objects are closed and disposed
'even if there is an error
Dim dt As New DataTable
Using cn As New MySqlConnection("Your connection string")
'Pass the Select statement and the connection to the constructor of the command
Using cmd As New MySqlCommand("Select name from table1 where dateofentry between #Date1 AND #Date2;", cn)
'Use parameters
cmd.Parameters.Add("#Date1", MySqlDbType.Date).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Date2", MySqlDbType.Date).Value = DateTimePicker2.Value
'open the connection at the last possible moment
cn.Open()
'Execute scalar only returns the first row, first column of the result set
dt.Load(cmd.ExecuteReader)
End Using
End Using
'Then a little link magic to dump the first column of the table
'to an array
Dim names() = (From row In dt.AsEnumerable()
Select row(0)).ToArray
'If there are less than 5 records returned this
'code will fail, Add a check for this and
'adjest your code accordingly
TextBox1.Text = names(0).ToString
TextBox2.Text = names(1).ToString
TextBox3.Text = names(2).ToString
TextBox4.Text = names(3).ToString
TextBox5.Text = names(4).ToString
End Sub
SELECT *
FROM `tblPerson`
WHERE (date_field BETWEEN '2018-12-30 14:15:55' AND '2019-01-06 10:15:55')
LIMIT 5;
text1.text = dt.Rows[0]["name"].ToString();
text2.text = dt.Rows[1]["name"].ToString();
text3.text = dt.Rows[2]["name"].ToString();
text4.text = dt.Rows[3]["name"].ToString();
text5.text = dt.Rows[4]["name"].ToString();
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