Data Reader formatting output - sql

I'm using the following function to generate a list of users connected to a selected database. How would I change this to a single line for multiple identical results?
For example: "sa (3) - MYCOMPUTER" rather than listing "sa - MYCOMPUTER" three times?
Function ConnectedUsers(ByVal SelectedDatabase As String, ByVal SelectedInstance As String)
Dim myCommand As SqlCommand
Dim dr As SqlDataReader
Dim mystring As String = String.Empty
Try
Dim myConn As New SqlConnection(ConnectionString)
myConn.Open()
myCommand = New SqlCommand("select loginame,hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & ";", myConn)
dr = myCommand.ExecuteReader()
While dr.Read()
mystring += GetFullName(dr(0).ToString().Trim()) & " - " & dr(1).Trim() & vbCrLf
End While
dr.Close()
myConn.Close()
Catch e As Exception
MessageBox.Show(e.Message)
End Try
Return mystring
End Function
Thanks.

The SQL Command should be
select loginame, count(*) as Nbr, hostname from sysprocesses where db_name(dbid) = '" & SelectedDatabase & "' group by loginame;"
and you should change the display to show the count (Nbr in this example) to be something like:
mystring += GetFullName(dr(0).ToString().Trim()) & "(" & dr(1).Trim() & ") - " & dr(2).Trim() & vbCrLf

Related

i want to filter my data with this from using visual studio 2015

I want to sort the data in the database with the date as the main condition with 2 date time picker 1 as the starting date and the other as the limit with this code by using between but I do not know the correct query form...my from looks like this the first DTP name is DTPDari and second DTPSampai
Call KONEKSI()
CMD = New OleDbCommand("SELECT * FROM Pembayaran where tanggal_pembayaran BEETWEEN '" & DTPDari.Value & "'AND tanggal_pembayaran = '" & DTPSampai.Value & "'", CONN)
DR = CMD.ExecuteReader
DR.Read()`
From the little what I understand from your question you can use any of the below
(syntax not tested)
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran BETWEEN '" & DTPDari.Value & "' AND '" & DTPSampai.Value & "')
or
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran > '" & DTPDari.Value & "') and (tanggal_pembayaran < '" & DTPSampai.Value & "')
Adding Function sample asper your request
Sub GetDetails()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString.ToString()
Dim connection As New SqlConnection(connectionString)
Dim queryString2 = "SELECT *
FROM dbo.Customers
WHERE (CreationDate BETWEEN #param1 AND #param2)"
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandText = queryString2
cmd.Connection = connection
cmd.Parameters.AddWithValue("#Param1", from_DateTimePicker.Value.Date)
cmd.Parameters.AddWithValue("#param2", to_DateTimePicker.Value.Date)
connection.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
'here fill on datatable Or anything you want
End While
connection.Close()
End Sub

MysqlDataReader.Read stuck on the last record and doesnt EOF

i confused why mySqlDataReader.Read stuck on the last record and doesnt EOF ..
Here's my private function for executeSql :
Private Function executeSQL(ByVal str As String, ByVal connString As String, ByVal returnRecordSet As Boolean) As Object
Dim cmd As Object
Dim objConn As Object
Try
If dbType = 2 Then
cmd = New MySqlCommand
objConn = New MySqlConnection(connString)
Else
cmd = New OleDbCommand
objConn = New OleDbConnection(connString)
End If
'If objConn.State = ConnectionState.Open Then objConn.Close()
objConn.Open()
cmd.Connection = objConn
cmd.CommandType = CommandType.Text
cmd.CommandText = str
If returnRecordSet Then
executeSQL = cmd.ExecuteReader()
executeSQL.Read()
Else
cmd.ExecuteNonQuery()
executeSQL = Nothing
End If
Catch ex As Exception
MsgBox(Err.Description & " #ExecuteSQL", MsgBoxStyle.Critical, "ExecuteSQL")
End Try
End Function
And this is my sub to call it where the error occurs :
Using admsDB As MySqlConnection = New MySqlConnection("server=" & rs("server") & ";uid=" & rs("user") & ";password=" & rs("pwd") & ";port=" & rs("port") & ";database=adms_db;")
admsDB.Open()
connDef.Close()
rs.Close()
'get record on admsdb
Dim logDate As DateTime
Dim str As String
str = "select userid, checktime from adms_db.checkinout in_out where userid not in (select userid " &
"from adms_db.checkinout in_out join (select str_to_date(datetime,'%d/%m/%Y %H:%i:%s') tgl, fid from zsoft_bkd_padang.ta_log) ta " &
"on ta.fid=userid and tgl=checktime)"
Dim rsAdms As MySqlDataReader = executeSQL(str, admsDB.ConnectionString, True)
Dim i As Integer
'This is where the error is, datareader stuck on the last record and doesnt EOF
While rsAdms.HasRows
'i = i + 1
logDate = rsAdms(1)
'save to ta_log
str = "insert into ta_log (fid, Tanggal_Log, jam_Log, Datetime) values ('" & rsAdms(0) & "','" & Format(logDate.Date, "dd/MM/yyyy") & "', '" & logDate.ToString("hh:mm:ss") & "', '" & logDate & "')"
executeSQL(str, oConn.ConnectionString, False)
rsAdms.Read()
End While
'del record on admsdb
str = "truncate table checkinout"
executeSQL(str, admsDB.ConnectionString, False)
End Using
i'm new to vbnet and really have a little knowledge about it,, please help me,, and thank you in advance..
The issue is that you're using the HasRows property as your loop termination expression. The value of that property never changes. Either the reader has rows or it doesn't. It's not a check of whether it has rows left to read, so reading has no effect.
You are supposed to use the Read method as your flag. The data reader begins without a row loaded. Each time you call Read, it will load the next row and return True or, if there are no more rows to read, it returns False.
You normally only use HasRows if you want to do something special when the result set is empty, e.g.
If myDataReader.HasRows Then
'...
Else
MessageBox.Show("No matches found")
End If
If you don't want to treat an empty result set as a special case then simply call Read:
While myDataReader.Read()
Dim firstFieldValue = myDataReader(0)
'...
End While
Note that trying to access any data before calling Read will throw an exception.

How to create parameterized queries with excel ? (VB.NET)

I'm trying to use parameterized queries to run faster update clauses in an Excel sheet... but when trying to do , vb.net says "Operation must use an updateable query".
With regular queries with concatenations , the query works:
Protected Friend Sub reemplazarDato(ByVal columna As String, ByVal dato As String, ByVal con As String)
Dim cmd As String = ""
conexion.Open()
For Each itm In arrayErrores
cmd = "UPDATE [" & obtenerHojaActual(columna, con) & "$] SET [" & columna & "]='" & dato & "' WHERE [" & columna & "]='" & itm & "'"
Try
Dim comando As New OleDbCommand(cmd, conexion)
comando.ExecuteNonQuery()
comando.Dispose()
Catch ex As Exception
repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog()
End Try
Next
conexion.Close()
End Sub
But when I try this way, the query dont work... ("Operation must use an updateable query")
Protected Friend Sub reemplazarDato(ByVal columna As String, ByVal dato As String, ByVal con As String)
Dim cmd As String = ""
Dim hoja As String = obtenerHojaActual(columna, con)
Dim comando As New OleDbCommand
comando.Connection = conexion
conexion.Open()
For Each itm In arrayErrores
cmd = "UPDATE [" & hoja & "$] SET [#columna]=#dato WHERE [#columna]=#itm"
comando.CommandText = cmd
comando.Parameters.Add("#columna", OleDbType.VarChar, columna.Length).Value = columna
comando.Parameters.Add("#dato", OleDbType.VarChar, dato.Length).Value = dato
comando.Parameters.Add("#itm", OleDbType.VarChar, itm.ToString.Length).Value = itm
Try
comando.ExecuteNonQuery()
comando.Parameters.Clear()
Catch ex As Exception
repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog()
End Try
Next
conexion.Close()
comando.Dispose()
End Sub
how can I do this with excel?
It is not valid to parameterize the column name - i.e. columna needs to be set using string concatenation as in your first code block, and not as a parameter. Also, you don't need to define the SQL and command parameters for each iteration - just define them once and set the value each time around the loop.
Protected Friend Sub reemplazarDato(ByVal columna As String, ByVal dato As String, ByVal con As String)
Dim hoja As String = obtenerHojaActual(columna, con)
Dim comando As New OleDbCommand
comando.Connection = conexion
comando.CommandText = "UPDATE [" & hoja & "$] SET [" & columna & "]=#dato WHERE [" & columna & "]=#itm"
comando.Parameters.Add("#dato", OleDbType.VarChar, dato.Length)
comando.Parameters.Add("#itm", OleDbType.VarChar, itm.ToString.Length)
conexion.Open()
For Each itm In arrayErrores
comando.Parameters("#dato").Value = dato
comando.Parameters("#itm").Value = itm
Try
comando.ExecuteNonQuery()
Catch ex As Exception
repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog()
End Try
Next
conexion.Close()
comando.Dispose()
End Sub

Vb.net show messagebox text and variable

Hi im new to vb and I want to display in my msgbox the text and variable but I can't seem to figure it out. My code is
Data = "UPDATE [Mc_Koy].[dbo].[User] SET [Balance] = [Balance] - '" & txt_fare.Text & "'WHERE [ID] = '" & txtbox_id.Text & "'"
Command = New SqlCommand(Data, Connection)
Command.ExecuteNonQuery()
Dim Data1 As String = "SELECT [Balance] FROM [Mc_Koy].[dbo].[User] Where [ID] = '" & txtbox_id.Text & "'"
Dim Command1 As New SqlCommand(Data1, Connection)
Command1.ExecuteNonQuery()
Dim dr As SqlDataReader
dr = Command1.ExecuteReader
With dr
.Read()
Dim f As Double
MsgBox("Current Balance is ", .Item(0))
.Close()
End With
But when I run it it only display the message "Current Balance is: "
I think you want to append it to the string, so use &:
MsgBox("Current Balance is " & .Item(0))

how to use multiple combo boxes to filter data

can someone please help me with this problem i'm a beginner in programming.
there is two comboboxes which is S.Y.(school year) and Sem(semester) and i want to use these two combo boxes to have more specific data in the listview below.
Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT edp_number, LastName + ', ' + FirstName as name, course as course, Address as address, syear as syear, Sem as sem FROM tblStudent"
If Me.cboSearchBy.Text = "1st" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%'"
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
this code only uses the sem combobox which is cboSearchby so now all i need to know is how to make combobox S.Y to function too and if also to use that texbox to search for firstname and lastname.
you just have to add another condition in your If statement:
If Me.cboSearchBy.Text = "1st" and Me.cboSY.Text = "2014-2015" Then
sSQL = sSQL & " where Sem like '1st" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
Else
sSQL = sSQL & " where Sem like '2nd" & Me.txtSearch.Text & "%' and SY like '" & Me.cboSY.Text & "%' "
End If
then if you want to add the searching for lastname and firstname, just add another condition on the IF-Statement.
Take Note: In using Logical Operator, AND is true if all condition is true while OR is true if atleast one of the conditions is true.