Microsoft Access (MySQL back end) queries with parameters - mysql

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")

Related

ALTER TABLE Syntax Error

I'm having trouble with an update query in Access.
I'm trying to do two things, add a field to a table, and change all values in another field to the same value.
ALTER TABLE 103 ADD COLUMN test TEXT;
UPDATE 103 SET [103].Workcenter = "103";
When I run these two lines independently, they work fine, but when I put them in the same query I get "Syntax Error in ALTER TABLE" statement. Does anyone know why I can't do this?
It would also be great if I could add a column and update all values in that field to a default value. I've tried DEFAULT in the ALTER TABLE command but it's not working either.
Thanks in advance for suggestions!
AS ron tornambe said, you can't have more than a single command in an Access Query. They do not support batching.
VBA code is your friend when doing alterations on tables: The Data Definition Language used in Access is more limited than what is available from VBA when directly manipulating the database objects.
For instance, to do exactly what you seek:
Public Sub AddFieldAndUpdate()
' Initialise '
Dim db As DAO.Database
Dim tb As DAO.TableDef
Dim fd As DAO.Field
Set db = CurrentDb()
' Get the 103 table '
Set tb = db.TableDefs("103")
' Create a new 'test' field, 128 char long '
Set fd = tb.CreateField("test", dbText, 128)
' Set the Default value for the new field '
fd.DefaultValue = "000"
' Add the new field to the 103 table
tb.Fields.Append fd
' Now do the update
db.Execute "UPDATE 103 SET [103].Workcenter = '103';", dbFailOnError
Debug.Print "Number of Updated records: " & db.RecordsAffected
' Cleanup
Set fd = Nothing
Set tb = Nothing
Set db = Nothing
End Sub
This is the jest of it, although you probably want to do more than that, for instance, set indexes, default formatting, etc as required.
Some table design features are only available when using the DAO object model to modify the TableDef. Others are only available when executing a DDL statement from an ADO connection.
Your table design change involves features which are available with either method. Use whichever you wish, but I would personally choose this way:
Dim strDdl As String
strDdl = "ALTER TABLE 103 ADD COLUMN test TEXT(128) DEFAULT ""000"";"
CurrentProject.Connection.Execute strDdl

How in VB.net we can encode string for SQL

For example, in sql
all ` should be replaced with `` right?
Well, is there a function built in by vb.net that does that sort of thing already?
That way I do not have to encode it.
By the way, I do not access sql database directly. Basically I am creating a text file and that text file contains raw sql statements. Most of the answers deal with accessing sql data directly.
I don't think so as I think the only case where something like this would be relevant is if you were doing inline SQL Commands without parameters.
This has a risk of SQL Injection, and therefore you should create commands like this:
Dim cmd As New SqlCommand("UPDATE [TableA] SET ColumnA=#ColumnA WHERE ID=#ID", Conn)
cmd.Parameters.Add("#ColumnA", SqlDbType.NVarChar).Value = txtColumnA.Text
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ID
cmd.ExecuteNonQuery()
Dont try and do this! I know you are trying to avoid SQL Injection so you are to be commended for thinking about security. However rolling your own sanitisation routine is something that is easy to get wrong.
Use parameters in your query along the lines of
cmd.CommandText = "select * from customer where id=?id";
cmd.Parameters.AddWithValue("?id",CustomerIDValue);
If you are using a string then you'll be using " in your code so you won't need to escape these characters.
Dim mySql As String = "SELECT `MyColumn` FROM `Table`"

sql Query in VBA code

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).

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.

vbscript to export an access query to a tab delimited file not working

I have this code:
db = "C:\Dokumente und Einstellungen\hom\Anwendungsdaten\BayWotch4\Neuer Ordner\baywotch.db5"
TextExportFile = "C:\Dokumente und Einstellungen\hom\Anwendungsdaten\BayWotch4\Neuer Ordner\Exp.txt"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
strSQL = "SELECT * FROM tblAuction1"
rs.Open strSQL, cn, 3, 3
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile(TextExportFile, True)
a = rs.GetString
f.WriteLine a
f.Close
Which is meant to connect to an access database and produce a tab delimited text file. tblAuction1 is a query in the database, and definitly exists and is not misspelt in any way, but I get an error that it cannot be found or does not exist. When I change it to tblAuction which is the name of the table, I get an error stating f.WriteLine a has been called incorrectly.
edit: I now only get a problem with f.writeline a, saying an incorrect argument has been supplied. I no longer have a problem with tblAuction1
edit: the sql code used for my query:
SELECT tblAuction.article_no, tblAuction.article_name, tblAuction.subtitle, tblAuction.current_bid, tblAuction.start_price, tblAuction.bid_count, tblAuction.quant_total, tblAuction.quant_sold, tblAuction.start, tblAuction.ends, tblAuction.origin_end, tblUser.user_name, tblAuction.best_bidder_id, tblAuction.finished, tblAuction.watch, tblAuction.buyitnow_price, tblAuction.pic_url, tblAuction.private_auction, tblAuction.auction_type, tblAuction.insert_date, tblAuction.update_date, tblAuction.cat_1_id, tblAuction.cat_2_id, tblAuction.article_desc, tblAuction.countrycode, tblAuction.location, tblAuction.condition, tblAuction.revised, tblAuction.paypal_accept, tblAuction.pre_terminated, tblAuction.shipping_to, tblAuction.fee_insertion, tblAuction.fee_final, tblAuction.fee_listing, tblAuction.pic_xxl, tblAuction.pic_diashow, tblAuction.pic_count, tblAuction.item_site_id
FROM tblUser INNER JOIN tblAuction ON tblUser.id = tblAuction.seller_id;
I have tried to reproduce this on several databases and machines, I can't get your code to fail.
Leaves :
a corrupt database, could you please run repair and try again ?
Fields in your database that are throwing of the query, I have tried several possibilities but can't find anything that brakes your code. To exclude other things you could try to create a new table and see if your code works on that table.
something wrong with your dll's , could you try it on another machine.
Answer (to see how we came to the answer see the comments)
There are unicode characters in your database that writeline does not accept because you created the textfile as ASCI.The characters in this case specifically where ♥♥♥
To make it work:
Set f = fs.CreateTextFile(TextExportFile, True, True)
P.S.
This question was answered earlier using the transfertext macro here
As Remou points out this looks like a cleaner solution. To make it work with non-default delimiters is a bit of a pain. First start exporting the query you like to export by right clicking and choose export. In the following dialogs specify the specifications and save these. When creating the macro select the specifications you just saved.
I think there is something wrong with the spaces in your connection string
Try this:
cn.Provider = "Microsoft.Jet.OLEDB.4.0"
cn.ConnectionString = db
cn.Open
HTH
Update:
Maybe there is a problem with the access rights to the database?
Or the mdb is already opened exclusively by another user (You with your access in design mode)?
Try this
cn.Open _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Persist Security Info=False;" & _
"Data Source=" & db