MS Access SELECT query DatePart - sql

i have some problem with my SELECT Query to MS Access .mdb file.
i am using VB.Net and have to send query like..
"SELECT d_date, d_tons, d_qty, d_cost FROM [deal] WHERE DatePart(""m"", [d_date]) = '" _
+ DTP.Value.Month.ToString + "' AND ([d_client] = '" + cBoxClient.Text + "')"
But it doesn't work.. No Error in compiling but this Query cannot SELECT any data.
DTP is DateTimePicker, i select Month with DTP and filled some text into cBoxClient(ComboBox)
What's wrong with that Query? i have no idea because i always used MySQL and this is my first application development with MS Access..
Please HELP me.

Use parameterized query, that will save you from sql injection and complexity of converting specific data format (such as DateTime) to it's string representation that is valid according to database specific culture. For example :
Dim queryString = "SELECT d_date, d_tons, d_qty, d_cost FROM [deal] WHERE " & _
"DatePart(""m"", [d_date]) = ? AND ([d_client] = ?)"
OleDbCommand cmd = New OleDbCommand(queryString, connection)
cmd.Parameters.AddWithValue("#date", DTP.Value.Month)
cmd.Parameters.AddWithValue("#client", cBoxClient.Text)

Related

Filter between dates VB.NET and Access database

As the title says, I'm unable to filter an SQL sentence from access database with vb.net
Dim data1 As String = DateTimePicker1.Value.ToShortDateString
Dim data2 As String = DateTimePicker2.Value.ToShortDateString
Dim sql As String = "SELECT totais.* From totais Where totais.data Between #" + data1 + "# And #" + data2 + "#;"
It gives me random values. If i put 1-10(October)-2019 it gives me all the records in system, if i put 12-10(October)-2019 it only gives today's record (doesn't show yesterday and before records). I'm not finding the problem, can you please help?
Thanks
I would use Parameters instead of concatenating a string for the Sql statement. It makes the statement much easier to read and avoids syntax errors.
With OleDb the order that parameters appear in the sql statement must match the order they are added to the parameters collection because OleDb pays no attention to the name of the parameter.
Private Sub OPCode()
Dim sql As String = "SELECT * From totais Where data Between #StartDate And #EndDate;"
Using dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand(sql, cn)
cmd.Parameters.Add("#StartDate", OleDbType.Date).Value = DateTimePicker1.Value
cmd.Parameters.Add("#EndDate", OleDbType.Date).Value = DateTimePicker2.Value
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
DataGridView1.DataSource = dt
End Using
End Sub
You need to use single quotes and convert type in SQL like this:
SELECT totais.* FROM totais WHERE totais.data Between CDATE('" + data1 + "') And CDATE('" + data2 + "');"
You should use parameters as per Mary's answer BUT for completeness...
Ms/Access requires dates specified as #mm/dd/yy# so your SQL will only work properly where the local date time format is mm/dd/yy. i.e. mostly the US. Otherwise you will have to format your date string.

SQL/ACCESS Get Value From Previous Row

Ok, so sweet and short. I'm writing a Forms App in VB and I'm connected to an ACCESS file. I need to get the value from the first select statement and use it in the second select statement. I know I can do this through the application itself but I'm looking to do it this way. Thanks in advance.
Dim cmd As New OleDbCommand(
"SELECT SSClass AS result
FROM Members
WHERE Names = '" + lstBoxMembers.SelectedItem.ToString() + "'
UNION
SELECT Names FROM Members WHERE SSClass= result ", conn)

Update Query in Visual Basic Express 2010

I'm trying to update an Access 2003 database using Visual Basic Express 2010 via SQL, I have so far got SELECT, DELETE and INSERT queries to work, but update will not...
con.ConnectionString = dbProvider & dbSource
con.Open() 'Open connection to the database
sqlstatement = "UPDATE users SET password = '" & NewPassword & "' WHERE USERID = " & ID & ";"
Dim dc As New OleDb.OleDbCommand(sqlstatement, con)
dc.ExecuteNonQuery()
con.Close()
Like I said, all other statements work, the error produced is:
http://i.stack.imgur.com/acFBT.png
Thank you!
The first problem is the word PASSWORD. It is a reserved keyword in MS-Access database. If you want to use it you should enclose it in square brackets.
Said that, please start using a parameterized query and not a string concatenation when you work with any type of database
So your code should be:
sqlstatement = "UPDATE users SET [password] = ? WHERE USERID = ?"
Using con = new OleDbConnection(dbProvider & dbSource)
Using dc = new OleDbCommand(sqlstatement, con)
con.Open()
dc.Parameters.AddWithValue("#p1", NewPassword)
dc.Parameters.AddWithValue("#p2", ID)
dc.ExecuteNonQuery()
End Using
End Using
You could read about the importance of Parameterized Queries and Sql Injection in many places, this link is a most famous one to start with

Parameter missing in ExecuteNonQuery command, using in VB.NET and Access

I have a very simple database in Access 2007 that I'm connecting to using VB 2010. There are two tables, MenuItems and Orders, and Orders.orderDate is of type "Date".
I'm running the following code in one of my VB forms (the connection string and everything else is fine):
sql = "SELECT OrderDate, MenuItem FROM MenuItems, Orders WHERE Orders.itemID = MenuItem.ID AND Orders.orderDate BETWEEN '" + fromDate + "' AND '" + toDate + "'"
Dim cmd As New OleDb.OleDbCommand(sql, con)
Dim count As Integer = cmd.ExecuteNonQuery()
But I get an error that:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters
Nothing seems to be missing. I've used the same code for another query, except the sql was different. But I think my sql is simple enough. Here's the sql that was generated in one instance (I've double checked, all table and column names are correct):
SELECT OrderDate, MenuItem From MenuItems, Orders WHERE Orders.itemID = MenuItem.ID AND Orders.orderDate BETWEEN '11/21/2012' AND '11/24/2012'
You should use parametrized queries for at least two reasons.
You don't have to worry about date (and other) literals and locale problems.
You don't have to worry about SQL injection attacks, where someone enters malicious code in a text box that turns a SQL statement into a harmful one.
Change your statement to
sql = "SELECT Orders.OrderDate, MenuItems.MenuItem " & _
"FROM MenuItems INNER JOIN Orders ON MenuItems.ID = Orders.itemID " & _
"WHERE Orders.orderDate BETWEEN ? AND ?"
Then execute the command like this
Dim fromDate, toDate As DateTime
fromDate = DateTime.Parse(fromDateTextBox.Text)
toDate = DateTime.Parse(toDateTextBox.Text)
Dim dataset As New DataSet()
Using conn As New OleDbConnection(connectionString)
Using adapter As New OleDbDataAdapter()
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add("?", fromDate)
cmd.Parameters.Add("?", toDate)
adapter.SelectCommand = cmd
adapter.Fill(dataset)
End Using
End Using
Well, the ExecuteNonQuery method is there for statements for changing data, ie. DELETE / UPDATE /INSERT, and the returned value are the number of rows affected by that statement.
Since you are using Select statement, you should be using oledbDataAdapter and Fil DataSet for use.
Dim conn As New OleDbConnection(con)
Dim adapter As New OleDbDataAdapter()
sql = "SELECT OrderDate, MenuItem FROM MenuItems, Orders WHERE Orders.itemID = MenuItem.ID AND Orders.orderDate BETWEEN '" + fromDate + "' AND '" + toDate + "'"
adapter.SelectCommand = new OleDbCommand(sql, con)
adapter.Fill(dataset)
Return dataset
The issue was a mis-spelled table. (MenuItem instead of MenuItems), but it didn't solve the question, I still got an error. It turned out to be a problem with matching formats between the database and the datepicker values being used as query parameters.
So I made sure I saved to the database in short Date Format:
sql = "INSERT INTO Orders(itemID, OrderDate) VALUES('" + ListBox1.SelectedValue.ToString() + "','" + FormatDateTime(OrderDate.Value, DateFormat.ShortDate) + "')"

VB.NET 2010 & MS Access 2010 - Conversion from string "" to type 'Double' is not valid

I am new to VB.Net 2010. Here is my problem: I have a query that uses a combo box to fetch many items in tblKBA. All IDs in the MS Access database are integers. The combo box display member and value member is set to the asset and ID of tblProducts.
myQuery = "SELECT id, desc, solution FROM tblKBA WHERE tblKBA.product_id = '" + cmbProducts.SelectedValue + "'"
In addition to getting items from the KBA table, I want to fetch the department details from the department table, possibly done in the same query. I am trying to do it in two separate queries.
myQuery = "select telephone, desc, website from tblDepartments where tblDepartments.product_id = tblProducts.id and tblProducts.id = '" + cmbProducts.SelectedValue + "' "
All help will be appreciated!
Change the '+' to a '&' then the compiler would be happy.
try adding .toString to cmbproducts.selectedvalue or do "tblKBA.product_id.equals(" & cmbProducts.selectedValue.toString & ")"
1.) Don't use string concatenation to build your query. Use parameters.
2.) I am guessing that tblKBA.product_id is a double and not a string, so don't put quotes around it.
myQuery = "SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = ?"
3 things. Test your value before building the select statement. Second, Use .SelectedItem.Value instead of .SelectedValue. Third, protect yourself from sql injection attack. Use parameters, or at the very least check for ' values.
If IsNumeric(cmbProducts.SelectedItem.Value) = False Then
'No valid value
Return
End If
myQuery = String.Format("SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = {0}", cmbProducts.SelectedItem.Value.Replace("'", "''"))