Vb.Net how to add another query to table? - mysql

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)

Related

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

how to insert data from datagridview to database mysql vb.net

here's my code
MysqlConn.Open()
command.Connection = MysqlConn
command.CommandText = CommandType.Text
command.CommandText = "INSERT INTO order VALUES (#1,#2,#3,#4,#5,#6,#7,#8)"
command.Parameters.AddWithValue("#1", rw.Cells(0).Value)
command.Parameters.AddWithValue("#2", rw.Cells(1).Value)
command.Parameters.AddWithValue("#3", rw.Cells(2).Value)
command.Parameters.AddWithValue("#4", rw.Cells(3).Value)
command.Parameters.AddWithValue("#5", Now())
command.Parameters.AddWithValue("#6", TextBox6.Text)
command.Parameters.AddWithValue("#7", TextBox7.Text)
command.Parameters.AddWithValue("#8", TextBox8.Text)
command.ExecuteNonQuery()
Next
MsgBox("done")
MysqlConn.Close()
command.Parameters.Clear()
i already did the "insert into order (names, .....) values (#1,....) but still not working. im using mysql
Dim I As Integer
For I = 0 To Dgrd.Rows.Count - 2
Dim row As DataGridViewRow = Dgrd.Rows(I)
Dim SQLCON As New SqlConnection(MyDataBaseCon)
Dim CMD As SqlCommand
Dim S1 As DataGridViewTextBoxCell = row.Cells(1)
Dim S2 As DataGridViewTextBoxCell = row.Cells(2)
Dim S3 As DataGridViewTextBoxCell = row.Cells(3)
CMD = New SqlCommand("Insert Into order
(S1,S2,S3) Values (#S1,#S2,#S3)", SQLCON)
SQLCON.Open()
CMD.Parameters.Add(New SqlParameter("#S1", SqlDbType.Int)).Value = S1
CMD.Parameters.Add(New SqlParameter("#S2", SqlDbType.Int)).Value = S2
CMD.Parameters.Add(New SqlParameter("#S3", SqlDbType.NVarChar, 50)).Value = S3
CMD.ExecuteNonQuery()
SQLCON.Close()
Next
MsgBox("done")

how to count all rows within the tables on a database then display in a textbox? [duplicate]

There are 10 rows in primary_student_table.
When I execute the following code, the result was -1.
Dim count As Int16
con.Open()
query = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1 "
cmd = New SqlCommand(query, con)
count = cmd.ExecuteNonQuery
MsgBox(count)
con.Close()
What's the problem in the above code?
You should be using ExecuteScalar() rather than ExecuteNonQuery() because you are fetching a value.
count = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
SqlCommand.ExecuteScalar Method
For proper coding
use using statement for proper object disposal
use try-catch block to properly handle exceptions
Example Code:
Dim connStr As String = "connection string here"
Dim query As String = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand()
With cmd
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
End With
Try
conn.Open()
Dim count As Int16 = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
Catch(ex As SqlException)
' put your exception here '
End Try
End Using
End Using
The solution is to replace
count = cmd.ExecuteNonQuery
with
count = cmd.ExecuteScalar
Like Robert Beaubien said in his comments
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=1234;database=dblms"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "Select * from dblms.accounts"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
the value in count will be the number of rows in a table :) hope this helped

How will i set a sql query as a variable in vb.net

Private Sub btncalc_Click(Sender,e)
a = val(txtConcode.Text)
b = val(txtConsumed.Text)
If a = 1 Then
Dim cmd as new mysqlcommand
cmd.connection = con
connect()
cmd.CommandText = "select Rate from tblrate where ConvertID=1"
dr = cmd.ExecuteReader
if dr.Read Then
q = dr.Read
end if
disconnect()
what i want to know is, how could i get the value from my sql query
and transfer it to the variable q
i just created the dr thing for example

Call a Stored Procedure to perform Count on an array

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