sql Query in VBA code - ms-access

If I want to code the following in VBA how do I do it
QUERY1:
SELECT field1, Min(field4) AS MinField4, Max(field5) AS MaxField5
FROM Table1
GROUP BY field1;
SELECT Query1.field1, Table1.field2, Table1.field3, Query1.MinField4,
Query1.MaxField5
FROM Query1 INNER JOIN Table1 ON (Query1.field1 = Table1.field1) AND
(Query1.MinField4 = Table1.field4) AND
(Query1.MaxField5 = Table1.field5);
I know for executing the SQL I store it as as string and write run SQL.
but how do I code storing query1 as a persistent object that can be referenced in other SQL statements?

Here some code that will fill up a dataset with your results
Dim cnn As ADODB.Connection
Dim recordset As ADODB.Recordset
Dim strSQL As String
Set cnn = CurrentProject.Connection
strSQL = "SELECT blah ..."
recordset.Open strSQL, cnn, adOpenKeyset, adLockOptimistic, adCmdText
'do what you want now.
oh yeah its been a while but you probably want to clean up too
Set recordset = Nothing
'etc..

I take it your question is "How do I create a new query in Microsoft Access using code?"
There are two solutions:
Microsoft Access will accept the DDL statement CREATE VIEW. So you can construct that statement in code and then execute it against the database via OLE DB e.g. ADO in VBA code.
The database object in MS Access contains a collections property called QueryDefs and you can access that to manipulate (and create) queries stored in the database.

you could just create a query and paste that SQL into the SQL View (available from the query design window).

Related

deleting items from sql table in VB.net

I am trying to remove all of the records from an SQL table in VB.net. My code for doing this is:
Dim SQL As String = "DELETE FROM MTable"
Using CN As New OleDb.OleDbConnection(AddPage.DBConnect)
CN.Open()
Dim DBcmd As New OleDb.OleDbCommand(SQL, CN)
DBcmd.ExecuteNonQuery()
CN.Close()
End Using
'SQLDataset.Tables("Mtable").Clear()
MtableTA.Update(SQLDataset)
SQL = "DELETE FROM ITable"
Using CN As New OleDb.OleDbConnection(AddPage.DBConnect)
CN.Open()
Dim DBcmd As New OleDb.OleDbCommand(SQL, CN)
DBcmd.ExecuteNonQuery()
CN.Close()
End Using
' SQLDataset.Tables("ITable").Clear()
ITableTA.Update(SQLDataset)
The Mtable and Itables are the SQL tables, while MtableTA and ItableTA are table adapters.
I also end up getting an error which states
An unhandled exception of type 'System.Data.DBConcurrencyException' occurred in System.Data.dll
Additional information: Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.
The section where this occurss is not provided in the code above, but is a call to MtableTA.update(SQLDataset). Any help would be very much appreciated. I'm also using OLEDB if that helps.
You have directly deleted the rows bypassing the TableAdapter methods to do that. So it is highly probable that when you call the Update there are some conflicts with data changed on the TableAdapter and no more available in the database.
After removing the rows directly using OleDbCommand.ExecuteNonQuery you should simply refresh the TableAdapters to sync them with the real situation on your physical database table
SQLDataset.Tables("ITable").Clear()
ITableTA.Adapter.Fill(SQLDataSet.ITable)

Retrieving Single Database/Cell from table mysql to Vb.net

I'm making a program in which the label text will change according to the retrieved data. But the only thing/command I found are retrieving data by column or by record. I need to get only a single data/cell.
I already know how to connect and use sql commands in Vb.net by as I said earlier I can't retrieve a single data/cell.
I found a function called mysql_fetch_array but I think It's only for Php not for Vb or I am I mistaken?
This will do it for you !
- you need the limit command added to your query !
- for better performance i suggest using order by !
Dim conn as MySqlConnection
Dim cmd As MySqlCommand
conn = New MySqlConnection("server=localhost;user id=root;password=;database=db_name;")
conn.Open()
cmd = New MySqlCommand("SELECT col_name FROM table_name WHERE col_name='values' LIMIT 1", conn)

Microsoft Access (MySQL back end) queries with parameters

I am trying to convert the back end of an Access database to MySQL. So far, I have no problems converting the tables, and updating the queries with no parameters to pass through queries.
However, I am at a lost at figuring out how to deal with queries with parameters requiring inputs from users.
Anyone could give me some pointers?
If you are inheriting back-end code that sends data to an Access DB there are few things to look out for.
Dates are handled differently in Access to MySQL.
Access requires that you enclose dates in ## like #05/05/2012#. In MySQL, just enclose them in single quotes, '05/05/2012'.
Column and table names that contain spaces are enclosed in squared brackets like [table name] in Access and backsticks like table name in MySQL.
For linked tables, something like:
SELECT ID, AText
FROM LinkedTable
WHERE AText=[Forms]![Form1]![txtText]
Should work quite well. There are limitations, in which case you will need a pass-through, but most queries can be written at the Access end just as if the table was a local MS Access table.
To code a pass-through, you might say:
Dim objconn As Object
Dim cmd As Object
''Late binding
Set objconn = CreateObject("ADODB.Connection")
objconn.Open ServerCon
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = objconn
cmd.CommandText = "InsertUser"
cmd.Parameters.Append _
cmd.CreateParameter("UserName", adVarChar, adParamInput, 50, "param1")

how to delete all DB rows via OpenRecordset (DAO)

How to delete all rows from table before starting inserting them?
Two things. First, DAO vs ADO is almost irrelevant. They are both available to Access up through Windows 7 and AFAIK there are no plans to remove them. Either should be OK to use in Access.
Secondly, you can just do this:
Public Sub Example()
With Access.CurrentDb
.Execute "DELETE Table2.* FROM Table2;"
.Execute "INSERT INTO Table2 ( fld1, fld2 ) SELECT Table1.ID, Table1.MyField FROM Table1;"
End With
End Sub
You could just to this:
Public Sub Example()
With Access.DoCmd
.RunSQL "DELETE Table2.* FROM Table2;"
.RunSQL "INSERT INTO Table2 ( fld1, fld2 ) SELECT Table1.ID, Table1.MyField FROM Table1;"
End With
End Sub
But the Execute method throws more informative error messages (and if you still care, is DAO).
If you are programming vba I assume that you are working with Adodb or simply ADO.
Therefore in order to delete a table records you can use a command object to do that.
Dim cnn as Connection
Dim cmd as Command
Set cnn=new Connection()
cnn.ConnectionString="ConnectionString"
cnn.Open()
Set cmd=new Command()
cmd.ActiveConnection=cnn
cmd.CommandText="DELETE FROM MyTable"
cmd.Execute()
cnn.Close()
Updated:
In order to use ADO objects you should add a reference to ADODB library
DAO Recordsets don't have an effective way to empty the table, as far as I know. If it's a small table, you can probably delete record-by-record, but I would find that silly. I just use DoCmd.RunSQL to run a DELETE query. I would typically set SetWarnings to False temporarily, of course.
Since this is separate from DAO, I would see that operation through before opening the recordset properly.
Please try this:
Do While Not rs.EOF
rs.Delete
rs.MoveNext
Loop

Select ##Identity returning 0 for linked table in Access

I am using Access 2007 and have some linked tables to a mySQL database. I am using DAO to insert a record into a mySQL linked table and trying to retrieve the inserted PK using Select ##identity, but that select is returning 0.
Dim sql As String
Dim oDB As Database
Set oDB = CurrentDb
sql = "INSERT INTO Quotes ( CustomerID ) SELECT 1 AS Expr1;"
oDB.Execute sql
If oDB.RecordsAffected <> 1 Then
MsgBox "cannot create new quote"
Exit Function
End If
Dim rsNewID As DAO.Recordset
Set rsNewID = oDB.OpenRecordset("SELECT ##IDENTITY") ' Create a recordset and SELECT the new Identity
Dim intNewID As Long
intNewID = rsNewID(0).Value ' Store the value of the new identity in variable intNewID
'This value is 0, why?
I've seen another question like this, that has not been satisfactorily answered for me
SELECT LAST_INSERT_ID()
fredrik gets partial credit, for the mySQL statement. It's important to note that I am using DAO, so statements are processed by the JET engine and it does not support this statement. This needs to be run as a pass through query in Access in order to work though. After I made a pass through query with fredrik's select statement, that did the trick. I called this Access passthrough query from my DAO code and it worked.
I have not used mysql. So, translate what I say for mysql.
Is CustomerID an identity column (i.e. does it generate ID on its own)?
If so, use the function that returns the last generated ID.
##Identity function is what people use in SQL Server. I don''t know of equivalent in mysql.
See this
Looking at the code above, you need not open the 2nd recordset. The rsNewID1 should help you get the last inserted ID.
Hope this helps.