Search between two dates in access database using sql - vb.net

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

Related

How to take data from access data to Combobox

Public Class AdminP_Time2
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim sql As String
Dim dr As OleDbDataReader
Private Sub AdminP_Time2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb;Persist Security Info=False;")
conn.Open() 'opens the connection
sql = "SELECT * FROM LecturerName"
cmd = New OleDbCommand(sql, conn)
dr = cmd.ExecuteReader
If dr.Read = True Then
ComboBox1.Text = dr("LecturerName")
End If
why my combobox just show me 1 item ? can anyone help me ? i want take my access data to Combobox.
The reason that your own code doesn't work is that you're only reading one record. You need a loop, e.g.
While dr.Read()
ComboBox1.Items.Add(dr("LecturerName"))
End While
That said, your code should look more like this:
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb;Persist Security Info=False;"),
cmd As New OleDbCommand("SELECT * FROM LecturerName", conn)
conn.Open()
Using dr As OleDbDataReader = cmd.ExecuteReader()
Dim tbl As New DataTable
tbl.Load(dr)
With ComboBox1
.DisplayMember = "LecturerName"
.DataSource = tbl
End With
End Using
End Using
That will load the data into a DataTable and bind that to the ComboBox. You should also set the ValueMember of the ComboBox if you want to be able to access the PK value of the selected record via the SelectedValue of the ComboBox. You should also specify what columns you want to retrieve data from rather than using a wildcard unless you genuinely want every column.
Here is a good example.
Sub TryThis()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdf = db.QueryDefs("qryStaffListQuery”)
strSQL = "SELECT tblStaff.* ” & _
"FROM tblStaff ” & _
"WHERE tblStaff.Office='" & Me.cboOffice.Value & "’ ” & _
"AND tblStaff.Department='" & Me.cboDepartment.Value & "’ ” & _
"AND tblStaff.Gender='" & Me.cboGender.Value & "’ ” & _
"ORDER BY tblStaff.LastName,tblStaff.FirstName;”
End Sub
You can find all details from the link below.
http://www.fontstuff.com/access/acctut17.htm

ExecuteReader: CommandText property has not been initialized when trying to make a register form for my database

hello guys im trying to script a register form for my database and i came with this code >> so can anyone help ?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
Else
MsgBox("Already registered")
End If
End Sub
Edit your Code in this way..
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Insert will not retrieve any records it's a SELECT statement you want to use .I'll suggest you use stored procedures instead to avoid Sql-Injections.
ExecuteReader it's for "SELECT" queries, that helps to fill a DataTable. In this case you execute command before cmd.commandText is defined.
You should have define cmd.commandText before and use ExecuteNonQuery after, like this.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()
cn.Close()
cmd.CommandText should be assigned stored proc name or actual raw SQL statement before calling cmd.ExecuteReader
Update:
Change code as follows
....
cmd.Connection = cn
cmd.CommandText = "select * from TblToRead where <filter>" ''This is select query statement missing from your code
cn.Open()
dr = cmd.ExecuteReader ....
where <filter> will be something like username = "' & Request.form("username') & '" '
The error itself is happening because you're trying to execute a query before you define that query:
dr = cmd.ExecuteReader
'...
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Naturally, that doesn't make sense. You have to tell the computer what code to execute before it can execute that code:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
'...
dr = cmd.ExecuteReader
However, that's not your only issue...
You're also trying to execute a DataReader, but your SQL command doesn't return data. It's an INSERT command, not a SELECT command. So you just need to execute it directly:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
cmd.ExecuteNonQuery
One value you can read from an INSERT command is the number of rows affected. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Dim affectedRows as Int32 = cmd.ExecuteNonQuery
At this point affectedRows will contain the number of rows which the query inserted successfully. So if it's 0 then something went wrong:
If affectedRows < 1 Then
'No rows were inserted, alert the user maybe?
End If
Additionally, and this is important, your code is wide open to SQL injection. Don't directly execute user input as code in your database. Instead, pass it as a parameter value to a pre-defined query. Basically, treat user input as values instead of as executable code. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES(#Username,#Password)"
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = TextBox2.Text
(Note: I guessed on the column types and column sizes. Adjust as necessary for your table definition.)
Also, please don't store user passwords as plain text. That's grossly irresponsible to your users and risks exposing their private data (even private data on other sites you don't control, if they re-use passwords). User passwords should be obscured with a 1-way hash and should never be retrievable, not even by you as the system owner.
You're attempting to change the CommandText after you're executing your query.
Try this:
Private cn = New SqlConnection("Server=localhost;Database=test;UID=sa;PWD=secret")
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.CommandText = "select * from table1" ' your sql query selecting data goes here
Dim dr As SqlDataReader
cmd.Connection = cn
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows = 0 Then
InsertNewData(TextBox1.Text, TextBox2.Text)
Else
MsgBox("Already registered")
End If
End Sub
Private Sub InsertNewData(ByVal username As String, ByVal password As String)
Dim sql = "INSERT INTO User_Data(Username,Password) VALUES(#Username, #Password)"
Dim args As New List(Of SqlParameter)
args.Add(New SqlParameter("#Username", username))
args.Add(New SqlParameter("#Password", password))
Dim cmd As New SqlCommand(sql, cn)
cmd.Parameters.AddRange(args.ToArray())
If Not cn.ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cn.Close()
End Sub
This code refers the INSERT command to another procedure where you can create a new SqlCommand to do it.
I've also updated your SQL query here to use SqlParameters which is much more secure than adding the values into the string directly. See SQL Injection.
The InsertNewData method builds the SQL Command with an array of SQLParameters, ensures that the connection is open and executes the insert command.
Hope this helps!

Error on .ExecuteNonQuery() in SQL Update Query [duplicate]

This question already has an answer here:
ADD SQL QUERY STAT
(1 answer)
Closed 8 years ago.
I'm trying to update an Access database using a SQL query, whenever I click the save button, it generates an error
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
And highlights .ExecuteNonQuery(). Can you guys help me on this? I'm new to vb.net.
Thanks in advance.
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
con.Open()
MsgBox(empNum)
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim sqlQuery As String = "UPDATE tbl_empinfo SET EmpID='" & empNum & "', FirstName ='" & empFname & "', LastName='" & empLname & "', Department='" & empDept & "', Status='" & empStat & "', Years='" & empYears & "' WHERE EmpID ='" & empNum & "' "
Using cmd As New OleDbCommand(sqlQuery, con)
With cmd
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
.Parameters.AddWithValue("FirstName", empFname)
.Parameters.AddWithValue("LastName", empLname)
.Parameters.AddWithValue("Department", empDept)
.Parameters.AddWithValue("Status", empStat)
.Parameters.AddWithValue("Years", empYears)
.ExecuteNonQuery()
End With
End Using
sqlQuery = "SELECT * FROM tbl_empinfo "
Dim cmd1 As New OleDbCommand
Dim da As New OleDbDataAdapter
With cmd1
.CommandText = sqlQuery
.Connection = con
With SqlAdapter
.SelectCommand = cmd1
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
con.Close()
End Sub
your query syntax is wrong. Since you are using params, use placeholders in the SQL: (the question marks are not some 'etc' type thing, you use ? to mark parameters!):
Dim sqlQuery As String = "UPDATE tbl_empinfo SET FirstName = ?,
LastName=?, Department=?,
Status=?, Years=? WHERE empID = ?"
Note: Six parameters
' USING will dispose of the cmd when it is done with it
' ...can also set the SQL and connection props in the constructor:
Using cmd As New OleDbCommand(sqlQuery, con)
With cmd
' no reason to move Textboxes to a variable either:
.Parameters.AddWithValue("#p1", empFnameText.Text)
.Parameters.AddWithValue("#p2", empLnameText.Text)
.Parameters.AddWithValue("#p3", DeptText.Text)
.Parameters.AddWithValue("#p4", StatText.Text)
.Parameters.AddWithValue("#p5", yearstext.Text)
your missing 6th parameter:
.Parameters.AddWithValue("#p6", eNumText.Text)
.ExecuteNonQuery()
End With
End Using
I dont think Access supports named params, so you use dummy ones but be sure to AddWithValue in the order specified in the SQL string.
EDIT
You can just create a SQL string with the values embedded instead of using params which is sort of what your SQL string does. Params are much better (research SQL injection attacks), but your string method is wrong (and you cant mix methods). It should be:
Dim sqlQuery As String = "UPDATE tbl_empinfo " &
"SET FirstName = " & empFname & ", LastName=" & empLname
The variables have to be outside the quotes or you will be setting FirstName to the literal "empFname"

Check if value exist in DBF database

I am trying to check if value "IAV-1419" exist in second column (ColName) in database named PROMGL.DBF.
I get this error : No value give for one or more required parameters
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV"
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
I am stuck here, if anyone could please check this code for me.
are you sure that your connectionstring is correct????
Data Source=" & FilePath &
how connection string know the database where it point only to "C:\" i think is missing database name
Another personal suggestion make your code more simple to read in example :
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "[NALOG,C,8]"
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT * FROM PROMGL WHERE [NALOG,C,8] = #NAL", con
cmd.Parameters.AddWithValue("#NAL", "IAV-1419")
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
Label6.Text = "EXIST"
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
End Using
End Using
End Using

OleDBException 0x80040e10 No value Given

The first part of this works correctly, when the Textbox value is null. It throws an exception however, when i try to filter search using the second part of the if statement.
The reason the table var is set that way is because the user has the option to load different tables.
The textbox string is the search parameter.
Public Class form1
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= .\Service.accdb ;")
Dim da As New OleDbDataAdapter
Private Sub getdata()
Me.Refresh()
Dim dt As New DataTable
Dim cmd As New OleDbCommand
Dim table As String = ComboBox1.Text.ToString
Dim txt As String = TextBox1.Text.ToString
If TextBox1.Text = Nothing Then
con.Open()
da.SelectCommand = New OleDbCommand("select * from [" & table & "] ;", con)
con.Close()
Else
con.Open()
da.SelectCommand = New OleDbCommand("select * from [" & table & "] where (External like '%" & txt & "%' or Internal like '%" & txt & "%' or Code like '%" & txt & "%');", con)
con.Close()
End If
Try
da.Fill(dt)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
DataGridView1.DataSource = dt
End Sub
End Class
Any help would be appreciated.
EDIT
It seems that this bit of code is stopping it from searching correctly, however without it i cannot save to the DB..
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(da)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
So i am assuming i am missing a paramter from this section?