Run-time error '3065' Cannot execute a select query - ms-access

I have written lots of the queries but I'm struggling with this one.
I get the run-time error 3065 when I run the following sql.
Dim db As DAO.Database
Dim sqlstring As String
Set db = DBEngine(0).Databases(0)
sqlstring = "SELECT ebk.hr_leav_amnt AS hr_clia_hour, ebk.hr_leav_type, ebk.hr_leav_code, ebk.hr_empl_code, ebk.hr_loadg_amt AS hr_loadg_amt, 'Leave Pay' AS hr_provision, mst.hr_paym_code, mst.hr_base_hour, '' AS hr_splt_accr, mst.hr_leav_abbr, ype.hr_norm_pcnt, ype.hr_allw_amnt"
sqlstring = sqlstring + " FROM hrtlvebk AS ebk, hrtlvmst AS mst, hrtptype AS ype"
sqlstring = sqlstring + " WHERE ebk.hr_leav_code Like 'a%' And ebk.hr_leav_code = [mst].[hr_leav_code] And ebk.hr_leav_type Like '1%' And bk.hr_leav_type = [mst].[hr_leav_type] And ebk.hr_recd_type = 'a' And ebk.hr_lbkg_refn = 'ACCRUAL' And ebk.hr_from_dati >= 20140701 And ebk.hr_from_dati <= 20140730 And mst.hr_load_rule <> 'y' And mst.hr_paym_code = [ype].[hr_paym_code]"
sqlstring = sqlstring + " GROUP BY ebk.hr_leav_amnt, ebk.hr_leav_type, ebk.hr_leav_code, ebk.hr_empl_code, ebk.hr_loadg_amt, mst.hr_paym_code, mst.hr_base_hour, mst.hr_leav_abbr, ype.hr_norm_pcnt, ype.hr_allw_amnt"
db.Execute sqlstring, dbFailOnError
When I run statement with Query (SQL) it works fine. The only thing I change is the text in the where clause.. ('a%' - Query it is "a%")
Thank you in advance.
John

The message is true for SELECT queries you should use Openrecordset to be able to retrieve results of selection. Execute is for 'command' queries that don't return values.

Related

Query by date with ASP and MySQL

I need to make a query in a MySQL database returning records with the current date.
I found the command below and it works perfectly inside MySQL:
SELECT * FROM TBAvaliacoes WHERE DataHora = (Date_Format(Now(),'%Y-%m-%d'))
But when I do this inside ASP, it returns me the error below:
See how I am doing:
' ## LISTA RAMAIS
Set cmdListaAvaliacoes = Server.CreateObject("ADODB.Command")
cmdListaAvaliacoes.ActiveConnection = conn
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes WHERE DataHora = (Date_Format("&Now()&",'%Y-%m-%d'))"
response.write cmdListaAvaliacoes.CommandText
cmdListaAvaliacoes.CommandType = 1
Set rsListaAvaliacoes = Server.CreateObject("ADODB.Recordset")
rsListaAvaliacoes.Open cmdListaAvaliacoes, , 3, 3
If I enclose Now () in single quotation marks, it gives no error, but returns nothing.
Does anyone know how to get around this?
Awaiting,
If you want to call the Now() function defined by MySql then you shouldn't use the VB.NET function and concatenate its output to your sql. Just write the code exactly how you write it in the MySql Workbench
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = (Date_Format(Now(),'%Y-%m-%d'))"
If you want to pass a particular date then you need to format your date as expected by MySql
Dim myDate As DateTime = new DateTime(2019,8,10)
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = '" & myDate.ToString("yyyy-MM-dd") & "'"
But in this case the better approach is to use parameters (even if you have full control of what your date is)
Dim myDate As DateTime = new DateTime(2019,8,10)
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = #dat"
Dim prm = cmdListaAvaliacoes.CreateParameter("#dat", adDBDate, adParamInput)
prm.Value = myDate
cmdListaAvaliacoes.parameters.Append prm
Side note
A lot of time has passed from the last time I have used ADODB. So the parameter solution is how I remember it. Search on the net for more complete CreateParameter examples

Return value from Access SQL Select Query

I would like to save the result from the SELECT to a variable, in MS Access.
It should select the most recent offer price from the PriceFeed table where stock symbol in the table matches the selected item from the form comboBox.
Dim sq2 As Variant
sql = "SELECT PriceFeed.Offer FROM PriceFeed WHERE PriceFeed.StockSymbol = Me.CBSymbol.Column(1) AND DateTime =(SELECT MAX([PriceFeed.DateTime])FROM PriceFeed)"
DoCmd.RunSQL sq2
You can use DMax and DLookup:
RecentPrice = DLookup("Offer", "PriceFeed", "StockSymbol = " & Me.CBSymbol.Column(1) & " AND DateTime = DMax('DateTime', 'PriceFeed')")
To avoid errors if no CBSymbol has been selected:
RecentPrice = DLookup("Offer", "PriceFeed", "StockSymbol = " & Nz(Me.CBSymbol.Column(1), 0) & " AND DateTime = DMax('DateTime', 'PriceFeed')")

How to get dataset from MySql Query using variables

I have a query like this:
SET #a = (SELECT GROUP_CONCAT(Id) FROM MyTable1 WHERE Id < 10);
SELECT * FROM MyTable2 WHERE find_in_set(IdLite, #a);
SELECT * FROM MyTable3 WHERE find_in_set(IdLite, #a);
SELECT * FROM MyTable4 WHERE find_in_set(IdLite, #a);
I've tryed to use this code to get resut:
Using ds As DataSet = MySqlHelper.ExecuteDataset(CnStr, SqlStr)
but I get error:
Fatal error encountered during command execution.
Error message is:
Parameter '#a' must be defined.
I've also tryed:
SELECT * FROM MyTable2 WHERE find_in_set(IdLite,
#a := (SELECT GROUP_CONCAT(Id) FROM MyTable1 WHERE Id < 10));
SELECT * FROM MyTable3 WHERE find_in_set(IdLite, #a);
SELECT * FROM MyTable4 WHERE find_in_set(IdLite, #a);
but I get the same error.
What's the correct way to get result into a DataSet?
DataSet mydataset = new DataSet();
MySqlConnection myConnection = new MySqlConnection();
myConnection.ConnectionString = "************";
myConnection.Open();
string mySelectQuery = "SELECT * FROM table";
MySqlCommand myCommand = new MySqlCommand(mySelectQuery,myConnection);
MySqlDataAdapter adapter = new MySqlDataAdapter(myCommand);
adapter.Fill(mydataset, "table");
dataGridView1.DataSource = mydataset;
dataGridView1.DataMember = "table";
myConnection.Close();
You can have a look in the following links:
http://forums.codeguru.com/showthread.php?448008-How-do-i-load-mysql-data-into-a-dataset-then-into-a-datagrid
http://www.dotnetheaven.com/article/how-to-load-data-from-database-into-datagridview-in-vb.net
If my answer is correct then please masrk as correct. Thank you
The error is in the connection string.
The solution is to add ;Allow User Variables=True to the database name.
This way:
CnStr = "datasource=" + Server_Name + _
";username= " + UserDB + _
";password=" + Password + _
";database=" + Database_Name + ";Allow User Variables=True"

retrieving null date from database to vb.net

i am having a problem in recovering a null date from my database into datepicker in vb.net.
i was able to save a datein mysql with a null value but can't retrieve it to datepicker.
i tried this code but it doesn't work.
If reader.IsDBNull(0) Then
Return
Else
refdate.Text = reader.GetString("refdate")
End If
my code for retrieving is
Try
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
forid.Text = row.Cells("id").Value.ToString
Try
connection.Open()
Dim sel As String
sel = "select * from recordtracker where id ='" & forid.Text & "'"
com = New MySqlCommand(sel, connection)
reader = com.ExecuteReader
While reader.Read
Cancel.Show()
Clear.Hide()
rdate.Enabled = False
rfromtbx.Enabled = False
doctype.DropDownStyle = ComboBoxStyle.DropDown
ID.Text = reader.GetInt32("id")
doctype.Text = reader.GetString("Type_of_Document")
itemtbx.Text = reader.GetString("Items")
rfromtbx.Text = reader.GetString("Received_From")
rdate.Text = reader.GetString("Received_Date")
remarks.Text = reader.GetString("Remarks")
margnote.Text = reader.GetString("Marginal_Note")
reftotbx.Text = reader.GetString("Referred_To")
acttaken.Text = reader.GetString("Action_Taken")
'refdate.Text = reader.GetString("refdate")
'If reader.Read() Then
If reader.IsDBNull(0) Then
Return
Else
refdate.Text = reader.GetString("refdate")
End If
Delete.Show()
' End If
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
any help is appreciated.
For future use, this was the answer needed by the asker.
reader.IsDBNull(0) gets the value of index zero which I presume that refdate is not in the first index.
Using reader.GetString("refdate") gets the String value; therefore, when retrieving null value, it returns error so better use isDbNull(reader("refdate")) to check if the field is null or not. To get the String value, you can simply use reader("refdate").toString

Why would AccessDataSource return different results to query in Access?

I have a query to return random distinct rows from an Access database. Here is the query:
SELECT * FROM
(SELECT DISTINCT m.MemberID, m.Title, m.FullName, m.Address,
m.Phone, m.EmailAddress, m.WebsiteAddress FROM Members AS m INNER JOIN MembersForType AS t ON m.MemberID = t.MemberID WHERE
(Category = 'MemberType1' OR Category = 'MemberType2')) as Members
ORDER BY RND(members.MemberID) DESC
When I run this in Access it returns the rows in different order every time, as per the random sort order. When I run it through my web app however the rows return in the same order every time. Here is how I call it in my code-behind:
private void BindData()
{
using (AccessDataSource ds = new AccessDataSource("~/App_Data/mydb.mdb", GetSQLStatement()))
{
ds.DataSourceMode = SqlDataSourceMode.DataReader;
ds.CacheDuration = 0;
ds.CacheExpirationPolicy = DataSourceCacheExpiry.Absolute;
ds.EnableCaching = false;
listing.DataSource = ds.Select(new DataSourceSelectArguments());
listing.DataBind();
if (listing.Items.Count == 0)
noResults.Visible = true;
else
noResults.Visible = false;
}
}
I added in all that stuff about caching because I thought maybe the query was being cached but the result was the same. I put a breakpoint in the code to make sure the query was the same as above and it was.
Any ideas? This is driving me nuts.
When executing the ACE/Jet RND function against a new connection the same seed value is used each time. When using MS Access you are using the same connection each time, which explains why you get a different value each time.
Consider these VBA examples: the first uses a new connection on each iteration:
Sub TestDiff()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;Data " & _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Tempo\Test_Access2007.accdb"
.CursorLocation = 3
Dim i As Long
For i = 0 To 2
.Open
Debug.Print .Execute("SELECT RND FROM OneRowTable;")(0)
.Close
Next
End With
End Sub
Output:
0.705547511577606
0.705547511577606
0.705547511577606
Note the same value each time.
The second example uses the same connection on each iteration (the .Open and .Close statements are relocated outside the loop):
Sub TestSame()
Dim con As Object
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;Data " & _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Tempo\Test_Access2007.accdb"
.CursorLocation = 3
.Open
Dim i As Long
For i = 0 To 2
Debug.Print .Execute("SELECT RND FROM OneRowTable;")(0)
Next
.Close
End With
End Sub
Output:
0.705547511577606
0.533424019813538
0.579518616199493
Note different values each time.
In VBA code you can use the Randomize keyword to seed the Rnd() function but I don't think this can be done in ACE/Jet. One workaround is to use the least significant decimal portion of the ACE/Jet the NOW() niladic function e.g. something like:
SELECT CDBL(NOW()) - ROUND(CDBL(NOW()), 4) FROM OneRowTable
I would move the RND into the inner SELECT
SELECT * FROM
(SELECT DISTINCT m.MemberID, RND(m.MemberID) as SortOrder, m.Title,
m.FullName, m.Address, m.Phone, m.EmailAddress, m.WebsiteAddress
FROM Members AS m
INNER JOIN MembersForType AS t ON m.MemberID = t.MemberID
WHERE
(Category = 'MemberType1' OR Category = 'MemberType2')) as Members
ORDER BY
Members.SortOrder DESC
You can use time as one argument to the RND field
Dim Now As DateTime = DateTime.Now
Dim millSec As Integer = Now.Millisecond
finalQuery = "SELECT * FROM wordInfo ORDER BY Rnd(-(1000* ROUND(" + millSec.ToString("N") + ", 0)) * [ID])"
So here from date and time value, millisecond value is taken which will be integer and it is used in sql query by rounding it.
wordInfo is table name
ID is the column name in database table
This gives random order every time (since millisecond value is different) be it same connection or new connection.