VB.NET - where column_name and column_name2 between column_name2 (date) and column_name2 (date) - vb.net-2010

So, I tried to get the UID.Text and try to show timein.
I want try to do this where uid.text = uid timein >= yyyy-MM-dd and timein <= yyyy-MM-dd
See the Image below, so that you'll see the code and error.
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "Server=localhost; uid=xx; pwd=xx; database=studentdatabase; Convert Zero Datetime=True;"
Dim Adapter As New MySqlDataAdapter
Dim BSource As New BindingSource
Dim DT As New DataTable
Try
MySqlConn.Open()
Dim Query As String
Query = "Select TimeIN, TimeOUT from tbl_time where UID =" & TextBox_UID.Text & " between TimeIn = '" & DateTimePicker2.Text & "' And TimeIn ='" & DateTimePicker1.Text & "'"
MSCommand = New MySqlCommand(Query, MySqlConn)
Adapter.SelectCommand = MSCommand
Adapter.Fill(DT)
BSource.DataSource = (DT)
DataGridView_Search.DataSource = BSource
Adapter.Update(DT)
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try

The correct SQL syntax for your query would be this:
select * from tbl_time where uid=uid and timein between date1 and date2
Try using this code instead:
Query = "Select TimeIN, TimeOUT from tbl_time where UID =" & TextBox_UID.Text & " TimeIn between '" & DateTimePicker2.Text & "' And '" & DateTimePicker1.Text & "'"

Related

How to close the sqldatareader within Using statement?

I'd like to use this code to verify if duplication occurs or not before saving the data to the database. How am I supposed to close the sqldatareader? (As what the error shows me)
con.ConnectionString = "Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True"
cmd.Connection = con
con.Open()
Dim theQuery As String = "SELECT * FROM Profile WHERE RollNo=#RollNo AND Name=#Name"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#RollNo", TextBox1.Text)
cmd1.Parameters.AddWithValue("#Name", TextBox2.Text)
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
cmd.CommandText = "INSERT INTO Profile VALUES ('" & rollno & "' , '" & name & "' , '" & gender & "' , '" & address & "' , '" & phoneno & "' , '" & datereg & "' , '" & faculty & "' , '" & course & "' , '" & semester & "')"
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
i = cmd.ExecuteNonQuery()
End If
End Using
con.Close()
The error are referring to is because you must complete the execution of the data reader before you try to execute another command on the same connection.
Additionally there are some issues with your code:
It is strongly recommended you use and then dispose of SqlConnections as you use them, do not try to reuse these globally in your application. The ado.net SQL Server client library will handle connection pooling for you by default.
You need to use parameters with your insert just like you did on your select.
Do not to use AddWithValue when adding your parameters, instead use the constructor and also specify the sql data type. If RollNo is a number (like integer) then you should pass the value as an integer to your parameter. I assumed it was a string stored in a varchar.
Wrap all types that implement IDisposable in Using statements to ensure resources are always released. (In case any one wants to nitpick, no it is not required for SqlCommand in this case.)
Dim recordExists As Boolean
Using con As SqlConnection = New SqlConnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand("SELECT RollNo FROM Profile WHERE RollNo=#RollNo AND Name=#Name", con)
cmd.Parameters.Add("#RollNo", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox2.Text
con.Open()
Using reader As SqlDataReader = cmd.ExecuteReader()
recordExists = reader.HasRows
End Using
End Using
End Using
If recordExists Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
Using con As SqlConnection = New SqlConnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand("INSERT INTO Profile (RollNo, Name) VALUES (#RollNo, #Name)", con)
cmd.Parameters.Add("#RollNo", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox2.Text
con.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
End Using
End Using
End If
if you are using using then not need to close. because it internally close all connection. The code would be like this
using(var con=new Sqlconnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")){
cmd.Connection = con
con.Open()
Dim theQuery As String = "SELECT * FROM Profile WHERE RollNo=#RollNo AND Name=#Name"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#RollNo", TextBox1.Text)
cmd1.Parameters.AddWithValue("#Name", TextBox2.Text)
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
cmd.CommandText = "INSERT INTO Profile VALUES ('" & rollno & "' , '" & name & "' , '" & gender & "' , '" & address & "' , '" & phoneno & "' , '" & datereg & "' , '" & faculty & "' , '" & course & "' , '" & semester & "')"
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
i = cmd.ExecuteNonQuery()
End If
End Using
con.Close()}

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

Count no. of Rows on my Database table Between the selection of two Datetimepicker

How can I get the total Rows of date records on my database between the selection of two datetimepicker? I don't have any idea how to do this. Had been searching for an answer for about an hour but I cannot find the correct code. Please help me.
Here's my code:
Try
ConnDB()
If fromDate.Value > toDate.Value Then
MessageBox.Show("Invalid Date Selection", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Else
sqlqry = "SELECT * FROM tblAttendance WHERE WorkingDate BETWEEN='" & fromDate.Value.ToShortDateString & "' AND '" & toDate.Value.ToShortDateString & "'"
da = New OleDbDataAdapter(sqlqry, cnn)
Dim dt As New DataTable("tblAttendance")
da.Fill(dt)
dgvAttendance.DataSource = dt
Dim counter As Double
counter = dt.Rows.Count
TextBox1.Text = counter
End If
Catch ex As Exception
If cnn.State = ConnectionState.Open Then
cnn.Close()
End If
End Try
It only shows 0 value if I qoute as a comment this part of the code:
da = New OleDbDataAdapter(sqlqry, cnn)
Dim dt As New DataTable("tblAttendance")
da.Fill(dt)
dgvAttendance.DataSource = dt
You must format the string expressions of the date values to fit Access SQL:
sqlqry = "SELECT * FROM tblAttendance WHERE WorkingDate BETWEEN #" & fromDate.Value.ToString("yyyy'/'MM'/dd") & "# AND #" & toDate.Value.ToString("yyyy'/'MM'/dd") & "#"
or use parameters as already suggested.
Finally figured out, Thanks for the help.
Here's my new code which really works.
Try
ConnDB()
If fromDate.Value > toDate.Value Then
MessageBox.Show("Invalid Date Selection", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Else
sqlqry = "SELECT * FROM tblAttendance WHERE WorkingDate BETWEEN #" & fromDate.Value & "# AND #" & toDate.Value & "#"
da = New OleDbDataAdapter(sqlqry, cnn)
dt = New DataTable("tblAttendance")
da.Fill(dt)
Dim counter As Integer
counter = dt.Rows.Count
TextBox1.Text = counter
End If
Catch ex As Exception
If cnn.State = ConnectionState.Open Then
cnn.Close()
End If
End Try

Search between two dates in access database using sql

This is my code for search in access database 2010. My problem is that when I search between two datetimepicker the result is wrong in datagridview, I mean when I search from specific records between May and June it shows me records also from February.
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
Dim bookdetials As New frmContactDetails
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT contact_id, first_name , birth_date, book_num, send_from, no_answer, no_answer_by, rec, book_answer_name, book_answer_num, send_date, send_to, project_name FROM tblAddressBook"
If CheckBox1.Checked = True Then
sSQL = sSQL & " where project_name like '%" & Me.TextBox2.Text & "%' " & _
" AND birth_date between '" & DateTimePicker1.Text & "' AND '" & DateTimePicker2.Text & "'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
Label4.Text = dt.Rows.Count
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
datepicker text should be converted to datetime format in sql
I had the same problem, the solution was too silly but it worked
use text instead of datetime in the db
make sure the datetimepicker enters "short format" data

Data Reader formatting output

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