I'm trying to get some information from a mysql database to a report in access. But I can't figure out how to get the information there since I'm using DAO connections in vba and cant use linked tables.
I've tried storing the information into a string from the form that I already have the information at through a DAO connection directly to mysql db with no luck.
Private Sub Command67_Click()
DoCmd.Save
DoCmd.GoToRecord , , acNewRec
Me.Label39.Visible = True
Dim strWhere As String
strWhere = "[ID] = " & Me.[Id]
DoCmd.OpenReport "MyReport", acViewPreview, , strWhere
End Sub
I use preview in that code to see some result but what I would like to do is print directly to the printer since this is a client turn receipt i need those to print fast.
Again I can't use linked tables.
After investigating on your former questions (some should be linked to that question), I see the problem. You don't link the MySQL-Tables what would make things easier for you.
But you can still use queries! Just put your connection string (maybeGlobales.ConnStringin former questions) in the queriesODBC Connection Stringin query design->properties. That makes the query a passthrough-query that is passed to MySQL-Server directly, not using MDAC.
Just set the reportsRecordSourceto the name of the query.
You can also build the query in VBA, but you can't use a temporary QueryDef("") as you can't set the Reports-Recordset, so use a non temp one.
Example (assumes there is a QueryDef named QueryForReport):
Sub EditQueryDefPassthrough()
With CurrentDb.QueryDefs("QueryForReport")
.Connect = "ODBC;Driver={MySQL ODBC 5.3 ANSI Driver};" _
& "Server=YourServerName;" _
& "Database=YourDatabaseName;" _
& "User=YourMysqlUserName;" _
& "Password=MysqlPwdForUser;" _
& "Option=3;" ' adapt this to your MySQL ODBC Driver Version and server settings
.SQL = "SELECT `Field` FROM `TABLE` LIMIT 1,1;" 'put SQL here (MySQL SQL Dialect, not MS-Access!). You can't use Access functions here (like Replace(), ..., but those of MySQL like Concat().
End With
End Sub
The QueryDef needs to be set before the Report_Load Event, but in Report_Open should be sufficent (e.g. if you want to use OpenArgs for building the SQL-String)
Related
My access 2010 database has super massive bloat. It has gone from 44mb to 282mb in just a few runs of the VBA. Here is what I have set up:
Local tables - these calculate statistics on forms and generally don't move around too much.
Pass through queries - my personal suspect. While viewing a form, if the user clicks on a record I run a pass through query using the record the user clicked on. So user clicked on "joe", pass through query runs with sql string = "select * from sqlserver where name= " &[forms]![myform]![firstname]
After this query runs, my vba DELETES the pass through query, then recreates it after another record is selected. so the user goes back to the list of names, and clicks BRIAN. then my vba deletes the pass through query and creates another one to select all records named brian from sql server, using the same code as above.
Forms - my forms are using the pass through queries as sources.
Is what I'm doing not very smart? How can I build this better to prevent access from exploding in file size? I tried compact and repair, as well as analyze DB performance in access 2010. Any help at all is appreciated, I've been googling access2010 bloat and have read about temptables as well as closing DAO (which I am using, and which I did explicitly close). Thanks!
Here is some code for 1 of the forms i'm using -
Private Sub name_Click()
'set dims
Dim db As DAO.Database
Dim qdExtData As QueryDef
Dim strSQL As String
Dim qdf As DAO.QueryDef
'close form so it will refresh
DoCmd.Close acForm, "myform", acSaveNo
'delete old query so a new one can be created with the same name
For Each qdf In CurrentDb.QueryDefs
If qdf.Name = "QRY_PASS_THROUGH" Then
DoCmd.Close acQuery, "QRY_PASS_THROUGH", acSaveNo
DoCmd.SetWarnings False
DoCmd.DeleteObject acQuery, "QRY_PASS_THROUGH"
DoCmd.SetWarnings True
Exit For
End If
Next
Set db = CurrentDb
'sql for the data
strSQL = "select fields from (table1 inner join table2 on stuff=stuff and stuff=stuff) left join table3 on stuff=stuff and stuff=stuff where flag='P' and table.firstname = " & [Forms]![myform]![firstname]
Set qdExtData = db.CreateQueryDef("QRY_PASS_THROUGH")
'how you connect to odbc
qdExtData.Connect = "ODBC;DSN=server;UID=username;PWD=hunter2;"
qdExtData.SQL = strSQL
DoCmd.OpenForm ("names")
Forms!returns!Auto_Header0.Caption = "Names for " & Me.name & " in year " & Me.year
qdExtData.Close
db.Close
qdf.Close
Set db = Nothing
Set qdf = Nothing
End Sub
There no reason I can think of to not bind the form to a view and use the “where clause” of the open form command. It would eliminate all that code.
You could then simply use:
strWhere = "table.FirstName = '" & me.FirstName & "'"
Docmd.OpenForm "Names”,,,strWhere
Also, it makes little or no sense that a C + R does not return free space. Something else here is seriously wrong.
Also, you really don’t need to delete the query each time. Just assume that the pass-through ALWAYS exists and then use this:
strSQl = “your sql goes here as you have now”
Currentdb.Querydef("MyPass").SQL = strSQL
Docmd.Openform “your form”
The above is all you need. I count about 3 lines of code here that will replace all what you have now. Note that of course the connection string info is saved with the pass-though and does not need to be set or messed with each time.
I would also do a de-compile of your database. I have a short cut setup on all my dev machines so I can just right click to de-compile. Here is some info on de-compile:
http://www.granite.ab.ca/access/decompile.htm
So really, I don’t know why you not using the where clause of the open form? Just bind the form to a SQL view without any conditions. Then use the open form command – you only pull records down the network pipe that match your criteria.
And note how you can stuff your SQL directly into the .SQL property of the query def as above shows – again no need for that delete code and this also means you don’t mess with connection info in code either. Again about 3 lines in total.
I'm running MS Access 2007, connecting to a MS SQL 2008 R2 server. I have a form with a multiselect box that I use to update status for several fields for the servers selected. Currently I'm using the ServerName field in the multiselect box. The problem is that there can be multiple records with the same server name. So to get around this I want to change it from ServerName to record number (ID). When I do this though VB gives the error "Error 3622 - You must use the dbSeeChanges option with OpenRecordset when accessing a SQL Server table that has an IDENTITY column". I've looked at many different posts on different websites, but can't figure out how to implement this into my code. The script works perfectly when I use ServerName, it also works perfectly if I go to the SQL server and change the field to Identity = False. The problem with that is that I can't create new records with the autonumber. It also works perfectly if I hard code the line numbers in an Update query. The problem with that is I can't hardcode the line numbers for everyone that uses the database. The issue only appears to be related to VB.
Below is what I have currently. As you can see I tried adding the dbSeeChanges to the Execute line.
Private Sub btnRoarsStatus_Click()
Dim strSQL As String
Dim Criteria As String
Dim Itm As Variant
With Me.lstServerNames
If .ItemsSelected.Count > 0 Then
For Each Itm In .ItemsSelected
Criteria = Criteria & "," & .ItemData(Itm)
Next Itm
' remove leading comma
Criteria = Mid(Criteria, 2)
' execute the SQL statement
strSQL = "UPDATE buildsheet SET [Roars Status] = " & Chr(34) & _
Me.cboRoarsStatus & Chr(34) & " WHERE ID IN(" & Criteria & ")"
Debug.Print strSQL
CurrentDb().Execute strSQL, dbSeeChanges
Else
MsgBox "You must select one or more items in the list box!", _
vbExclamation, "No Selection Made"
Exit Sub
End If
End With
MsgBox "Completed", vbExclamation, "Completed"
End Sub
I had a similar Problem with a Delete Statement that I wanted to execute and solved it by:
CurrentDb.Execute SqlStr, dbSeeChanges
note the missing () after CurrentDb
For me worked this:
CurrentDb.Execute strSQL, **dbFailOnError +** dbSeeChanges
dbFailOnError was the key...
CurrentDb().Execute strSQL, someotherConstant, dbSeeChanges
I think, someotherConstant maybe missing.
In MS Access 2010, I am building an update query (using the Query Designer).
I would like to pass the name of the column to update as a variable, at run time.
I have tried writing the SQL and running the query in VBA. This seemed like the easiest way... however the SQL to complete the update becomes quite messy. I would prefer to do this in the query builder GUI .
Is it possible?
I have so far tried entering field names into the query builder:
expr1:[field_name]
Although Access prompts me for "Field_name" This results in "Cannot update 'field_name'; field not updateable.
Also, I tried this method:
Expr1: "'" & [field_name] & "'"
which results in "'" & [field_name] & "'" is not a valid name; check for punctuation.. etc
Below is a screen capture the query I am trying to build.
Access' db engine will not allow you to use a parameter as the name of the target field for your UPDATE statement.
If you try a user-defined function instead of a parameter to provide the field name, the result will be the same ... no joy.
It seems the db engine will not resolve object names when it executes a SQL statement. That limitation applies not just to field names, but table names as well. IOW, the following query will fail with an error message that it "cannot find the input table or query 'give me a table name'".
SELECT *
FROM [give me a table name];
While that isn't exactly the same as your situation, I suspect the reason may be. The db engine is too limited about resolving object names when it plans/executes queries.
Perhaps the best method is to use SQL, build your prompts and then assign these values to variables in VBA, then just add the variable value into your SQL.
So something along these lines. Your using Update query but same logic
Dim SQL as string
dim **FieldName** as string
SQL = "Select [table]![" & Chr(34) & **FieldName** & Chr(34) & "] from ........"
Check Here for SQL building tips
I use this method frequently - I know it's a very old post, but hope this helps someone - building on what David said:
Sub CreateQuery
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set dbs = CurrentDb
Set qdf = dbs.CreateQueryDef("NameOfNewQuery")
strSQL = "Select " 'notice the space
strSQL = strSQL & "FROM " 'notice the sapce
strSQL = strSQL & "WHERE;"
qdf.SQL = strSQL
qdf.Close
Set qdf = Nothing
Set dbs = Nothing
End Sub
I am using the following code in Access to try to open a recordset:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("fieldHistory")
I consistently get the error "Too few parameters."
fieldHistory is a query with the SQL code as follows:
SELECT Date, User, Type
FROM Inventory
WHERE ((Inventory.Type) In ("Insert","EditTo"));
I have looked into this some - I have found that if I use the code db.OpenRecordset("Select * from Inventory") I do not get an error.
Also, I found this forum which seemed to be on to something but I couldn't understand how to create the appropriate querydef objects to create my query.
http://access.mvps.org/access/queries/qry0013.htm
Thank you very much!
Date, User, and Type are all special words or reserved words in MS Access. DO NOT use them for your field names.
You may have some success by enclosing each of them in brackets but I highly recommend you change the field names instead.
Create a new database.
Open the new database and make sure you have DAO included in the references.
Insert a new standard module, making sure to include Option Explicit in the Declarations section.
Then paste in this code and run it.
Public Sub CreateTableZack()
Dim strSql As String
strSql = "CREATE TABLE tblZack (" & vbNewLine & _
vbTab & "id COUNTER CONSTRAINT pkey PRIMARY KEY," & vbNewLine & _
vbTab & "foo_text TEXT(255)," & vbNewLine & _
vbTab & "date_assigned DATETIME);"
Debug.Print strSql
CurrentProject.Connection.Execute strSql
End Sub
Assuming the table is created successfully, create qryZack with this as its SQL:
SELECT *
FROM tblZack;
Then try your code to open a DAO recordset based on qryZack.
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("qryZack")
Does it work?
If not, your Access installation may be hosed ... you may need to repair or reinstall it. You could also try this on another machine which has Access available, if you can.
If it works with the new database, but not your old one, the old one may be corrupted. Make a backup copy first, then try Compact & Repair.
Another issue is your field names. Date, User and Type are all Access reserved words. See Problem names and reserved words in Access. I can't say those names are causing problems here, but using reserved names for database objects (tables, fields, queries, etc.) can have dramatic consequences ... like it confuses the crap out of Access. So I fastidiously avoid them.
Edit: You should also check the references in your old database. Missing/broken references also confuse the crap out of Access.
I am getting an vba error 3271; Invalid property value. This happens when trying to append a memo field in a querydef. Any ideas on how to get around this?
Example:
public sub TestMemoField
Dim qdf As QueryDef
Set qdf = CurrentDb.QueryDefs("AppendRecord")
qdf.Parameters("#SomeBigText").value = string(1000,"A")
qdf.Execute
end sub
Thanks in advance.
Apparently you cannot have a parameter longer than 255 characters ( http://support.microsoft.com/kb/275116 ).
It is possible to use a recordset, or to use:
qdf.SQL="INSERT INTO Sometable (SomeField) Values('" & String(1000, "A") & "')"
Um, what are you trying to do? Why are you using parameters? Why not just execute SQL in code, like this:
Public Sub TestMemoField
Dim strSQL As String
strSQL = "UPDATE MyTable SET MyField='" & String(1000,"A") & "'"
CurrentDb.Execute strSQL, dbFailOnError
End Sub
I don't use parameters in saved queries except when I need to pull a value from a control on a form to be used in a saved query.
Now, my answer might not be good if your back end is not Jet or if there's something about the actual criteria and structure of your saved query that makes it important to use a saved query instead of simply using on-the-fly SQL. But you've provided virtually no information (including omitting the SQL of the querydef you're executing), so it's rather difficult to supply any kind of helpful answer.