how to use date in where clause to search data from access data base in vb.net? - vb.net

i want to search data from my data base using date in where clause.
But i am getting an error while executing the code.
I am trying this code.
Sub comboboxSELECTED()
Dim a As Date
Form1.ComboBox1.Text = a
Dim con As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Mdm.accdb"
con.Open()
Dim q As String = "select * from Rice Where DateReceived =" & Form1.ComboBox1.SelectedText
Dim cmd As New OleDb.OleDbCommand(q, con)
Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
While Reader.Read
Form1.ListView1.Items.Add(Reader(0))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(1))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(2))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(3))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(4))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(5))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(6))
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(Reader(7))
Form1.DateTimePicker1.Text = Reader("DateReceived")
Form1.TxtEnrolment.Text = Reader("Enrolment")
Form1.TxtReceived.Text = Reader("QtyReceived")
Form1.TxtTotal.Text = Reader("TotalQuantity")
Form1.TxtUtilised.Text = Reader("QtyUtilised")
Form1.TxtBalance.Text = Reader("Balance")
End While
Reader.Close()
con.Close()
End Sub

Please try changing that section of code to this:
String q = "select * from Rice Where DateReceived = #datercvd";
OleDb.OleDbCommand cmd = New OleDb.OleDbCommand(q, con);
OleDbParameter objectdate = new OleDbParameter("#datercvd", OleDbType.DBDate);
objectdate.Value = Convert.ToDateTime(Form1.ComboBox1.SelectedText);
cmd.Parameters.Add(objectdate);
It does a match on the date, converts from a string, and takes care of SQL injection isues.

The VB.net code...
Private Sub ComboBoxSelected()
Using con As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Mdm.accdb"
Dim q As String = "Select * from Rice Where DateReceived =#DateReceived"
Using cmd As New OleDb.OleDbCommand(q, con)
cmd.Parameters.Add("#DateReceived", OleDbType.Date).Value = CDate(Form1.ComboBox1.SelectedText)
con.Open()
Using Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
While Reader.Read
'Your code
End While
End Using
End Using
End Using
End Sub

Related

How to check if byte is null vb.net

I'm assigning background images to every button according to my SQL Server database. If a byte is null I get this error:
Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
I want to allow buttons with no background images, but the error is preventing me.
Here is what I attempted:
Dim strsql As String
Dim ImgSql() As Byte
Using con As New SqlConnection("constring")
con.Open()
strsql = "SELECT Imagen FROM Inventario WHERE ID=#ID"
Dim cmd As New SqlCommand(strsql, con)
ItemID = 1
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ItemID
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
ImgSql = myreader("Imagen")
If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then
Dim ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
con.Close()
Else
'do nothing
End If
End Using
Dim ItemID As Integer = 1
Dim sql As String = "SELECT Imagen FROM Inventario WHERE ID=#ID"
Using con As New SqlConnection("constring"), _
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Integer).Value = ItemID
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
If myreader.Read() AndAlso Not DBNull.Value.Equals(myreader("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(myreader("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
End Using
End If
End Using
End Using
Based on this answer in C#, converted to vb.net and added NULL check
Using con As New SqlConnection("constring")
Using cmd = con.CreateCommand()
cmd.CommandText = "SELECT Imagen FROM Inventario WHERE ID=#ID"
Dim ItemID = 1
cmd.Parameters.AddWithValue("#ID", ItemID)
con.Open()
Dim res = cmd.ExecuteScalar()
If res IsNot Nothing Then
ImgSql = CType(res, Byte())
If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then
Dim ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
End If
End If
End Using
End Using

How do I get multiple values from query using OleDBConnection?

I have edited the previous code and tried this below, I have also changed the textbox into a listbox with the same name, but I now get no value in the listbox after running the below code:
myConnection.ConnectionString = providerEdit
Dim str As String
str = "SELECT [Email] FROM [PRD_Records] WHERE [ReceiveKMCWEMSAlerts] = Yes"
Using cmd As OleDbCommand = New OleDbCommand(str, myConnection)
myConnection.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While reader.Read()
txtCreateAnnTo.Text = reader(0).ToString
End While
reader.Close()
End Using
Thanks everyone for your responses.... I found the problem with the code, it was very simple and I was just overlooking it. I update the coded below: myConnection.ConnectionString = providerEdit
Dim str As String
str = "SELECT [Email] FROM [PRD_Records] WHERE [ReceiveKMCWEMSAlerts] = Yes"
Using cmd As OleDbCommand = New OleDbCommand(str, myConnection)
myConnection.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While reader.Read()
txtCreateAnnTo.Items.Add(reader(0).ToString)
End While
reader.Close()
End Using

Populate ListBox from SQL only items with condition (first character)

I've managed to put all items in a ListBox, also have the first character defined kto, how to insert only those values from List column into Listbox that begin with that character kto.
Just to mention that kto is value from 0 to 9, always a number.
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
cmd.CommandText = "SELECT List FROM Konta"
Dim kto = Left(Label1.Text, 1)
'Label3.Text = kto
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
Try this
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
Dim kto = Left(Label1.Text, 1)
cmd.CommandText = "SELECT List FROM Konta WHERE List LIKE '" & kto.toString & "%'"
ListBox1.Items.Clear
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
In your while loop, before adding the item in the listbox check the date type of reader("LIST") and add it only if matches the required type.
You can check the type using the following code:
reader.GetFieldType(0)

Error: No data exists for the row/column

I get the following error: No data exists for the row/column.
It should retrieve the image
sSql = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC"
Dim cmd As New OleDbCommand(sSql, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
dr.Read()
lab1id.Text = dr.GetValue(1).ToString
lab1fname.Text = dr.GetValue(2).ToString
lab1lname.Text = dr.GetValue(3).ToString
lab1position.Text = dr.GetValue(4).ToString
lab1subject.Text = dr.GetValue(5).ToString
dr.Close()
sSql = "select Pfile from Faculty where StId = '" & lab1id.Text & "'"
Dim pcmd As New OleDbCommand(sSql, con)
Dim pdr As OleDbDataReader = cmd.ExecuteReader()
pdr.Read()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
pdr.Close()
The dr.GetValue(N) is zero-based ordinal. Change your indices:
While dr.Read()
lab1id.Text = dr.GetValue(0).ToString
lab1fname.Text = dr.GetValue(1).ToString
lab1lname.Text = dr.GetValue(2).ToString
lab1position.Text = dr.GetValue(3).ToString
lab1subject.Text = dr.GetValue(4).ToString
End While
While pdr.Read() ' | you got a typo here. Change `dr` to `pdr`.
Dim bits As Byte() = CType(pdr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
End While
Consider changing your code to something like this:
Using command As OleDbCommand = con.CreateCommand()
command.CommandText = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC;"
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
lab1id.Text = reader.Item("id").ToString
lab1fname.Text = reader.Item("fname").ToString
lab1lname.Text = reader.Item("lname").ToString
lab1position.Text = reader.Item("position").ToString
lab1subject.Text = reader.Item("subject").ToString
End While
End Using
End Using
Using command As OleDbCommand = con.CreateCommand()
command.CommandText = "select Pfile from Faculty where StId = #StId;"
command.Parameters.AddWithValue("#StId", lab1id.Text)
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
Dim bits As Byte() = CType(reader.Item("Pfile"), Byte())
Using stream As New MemoryStream(bits)
imgRetrieve.Image = Bitmap.FromStream(stream)
End Using
End While
End Using
End Using
The problem is you never execute pcmd, see the following two lines:
Dim pcmd As New OleDbCommand(sSql, con)
Dim pdr As OleDbDataReader = cmd.ExecuteReader() ' cmd should be replaced with pcmd
I would suggest adding While...End While Statement when getting the values from dr and pdr. You also need to parameterize the second query to avoid SQL Injection.
sSql = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC"
Dim cmd As New OleDbCommand(sSql, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
lab1id.Text = dr.GetValue(1).ToString
lab1fname.Text = dr.GetValue(2).ToString
lab1lname.Text = dr.GetValue(3).ToString
lab1position.Text = dr.GetValue(4).ToString
lab1subject.Text = dr.GetValue(5).ToString
End While
dr.Close()
sSql = "select Pfile from Faculty where StId = #StId"
Dim pcmd As New OleDbCommand(sSql, con)
pcmd.Parameters.AddWithValue("#StId", lab1id.Text)
Dim pdr As OleDbDataReader = pcmd.ExecuteReader()
While pdr.Read()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
End While
pdr.Close()

Using SQLDataReader instead of recordset

I am new to this and had this question. Can I use SQLDataReader instead of a Recordset. I want to achieve the following result in an SQLDataReader.
Dim dbConn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sqlstr As String = "SELECT Name,Status FROM table1 WHERE id=" + item_id.Value.ToString
rs.Open(SQL, dbConn)
While Not rs.EOF
txtName.Text = rs.Fields.Item("Name").Value
ddlstatus.SelectedIndex = 1
rs.MoveNext()
End While
rs.Close()
rs = Nothing
dbConn.Close()
dbConn = Nothing
Can I replace recordset with SQLDataReader and if I can can you please show me the changes in code?
Its highly recommend that you use the using pattern:
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New SqlConnection(sConnection)
Con.Open()
Using Com As New SqlCommand("Select * From tablename", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txtName.Text = RDR.Item("Name").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
You will have to swap out a few things, something similar to the following.
Here is an example, you will need to modify this to meet your goal, but this shows the difference.
I also recommend using a "Using" statement to manage the connection/reader. Also, a parameterized query.
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Dim objCommand As New SqlCommand
objCommand.CommandText = "Select * From tablename"
objCommand.Connection = New SqlConnection(sConnection)
objCommand.Connection.Open()
Dim objDataReader As SqlDataReader = objCommand.ExecuteReader()
If objDataReader.HasRows Then
Do While objDataReader.Read()
Console.WriteLine(" Your name is: " & Convert.ToString(objDataReader(0)))
Loop
Else
Console.WriteLine("No rows returned.")
End If
objDataReader.Close()
objCommand.Dispose()
Dim rdrDataReader As SqlClient.SqlDataReader
Dim cmdCommand As SqlClient.SqlCommand
Dim dtsData As New DataSet
Dim dtbTable As New DataTable
Dim i As Integer
Dim SQLStatement as String
msqlConnection.Open()
cmdCommand = New SqlClient.SqlCommand(SQLStatement, msqlConnection)
rdrDataReader = cmdCommand.ExecuteReader()
For i = 0 To (rdrDataReader.FieldCount - 1)
dtbTable.Columns.Add(rdrDataReader.GetName(i), rdrDataReader.GetFieldType(i))
Next
dtbTable.BeginLoadData()
Dim values(rdrDataReader.FieldCount - 1) As Object
While rdrDataReader.Read
rdrDataReader.GetValues(values)
dtbTable.LoadDataRow(values, True)
End While
dtbTable.EndLoadData()
dtsData.Tables.Add(dtbTable)
msqlConnection.Close()
Return dtsData