Getting insertID using currentproject.connection - vba

I wanted to get the insert ID of the the last insert query
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Set cn = CurrentProject.Connection
cn.Execute "Insert into Locations(locationName) Values('" & Me.location.Value & "')"
rs.Open "SELECT ##identity AS locationID FROM locations", cn
Debug.Print rs.Fields("locationID")
However, this always returns 0 . Is there a way to get the insertID using the ADO connection?
Edit1:
With the help of the reply below and further research I found out the soultion
I forgot to mention that my backend database is mysql database not MSSQL or Access. I also changed my code to use global connection now which is named g_cn. I think currentproject.connection does not work with backend mysql database to get the insertionID because it uses DAO connection.
I set the global connection by doing:
g_cn.Open "DRIVER={MySQL ODBC 8.0 Unicode Driver};Server=" & gc_DevServerName & ";Database=" & gc_DevDBName & ";Uid=" & gc_DevUser & ";Pwd=" & gc_DevPassword & ";Option=3;"
I can now use ADO. So my code changed to :
Dim rs As New ADODB.Recordset
rs.Open "Insert into Locations(locationName) Values('" & Me.location.Value & "')", g_cn
rs.Open "Select LAST_INSERT_ID() as last from locations;", g_cn
Debug.Print rs.Fields("last")
rs.Close

SELECT ##identity is a special query in Access. You can't use it with a FROM clause. Remove that and the query will work:
rs.Open "SELECT ##identity AS locationID", cn

Related

Using ADODB within Access

I'm trying to use adodb connection withing access vba, and it doesn't return me anydata, I guess my problem would be the connection, even though i'm using CurrentProject.Connection.
Need help please, here is my code
Dim cnThisConnect As New ADODB.Connection
Dim rsExpenses As New ADODB.Recordset
Dim sQuery As String
sQuery = "SELECT [ShippingSoldPrice] , ShippingPurchaseTaxe FROM Vehicles LEFT JOIN Contacts AS C ON
Vehicles.CustomerID = C.ID"
sQuery = sQuery & " Where " & Me.Filter
Set cnThisConnect = CurrentProject.Connection
rsExpenses.Open sQuery, cnThisConnect, adOpenDynamic, adLockOptimistic
If Not rsExpenses.EOF Then
Try to remove the line containing the where clause maybe this is the problem
'sQuery = sQuery & " Where " & Me.Filter
then check the returning records, if there are records then the problem is in the filter conditions.
Hope this may help

SQL Select Statement in Microsoft Access VBA - Need help inserting in Access table as block, not loop

I am trying to do a Select statement from an SQL server using an ADODB connection, within Microsoft Access VBA. The select statement is very complex with calculations and would work better to keep that to try and turn in to a connection with the DB.
I can append the data row by row, but am wondering how I could append as simple as possible as a block of data to save time/vba effort. (Lots of data!)
In order to simplify the example, I have put a basic SQL statement, but if you could review this and let me know if there is a way to append as a recordset block or what would be a better option... The code below works for pasting as a block into excel, and I would think I only need to change that commented out line's method to append in Access...
Option Private Module
Private Const DataServer = "GLSSQLMADPS2"
Private Const sqlconstring = "Driver={SQL Server};Server=" & DataServer & "; Database=PERF_MGMT_BWRSRV_PROD; Trusted_Connection=yes; Connect Timeout = 600"
Sub M2DSQLPull()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sql As String
Dim sql As String
sql = "SELECT " & _
"Employee_Token_NR, " & _
"Null as 'Sum_Month', " & _
"1000 AS 'Data_ID', " & _
"DATEADD(m, DATEDIFF(m, 0, MIN(CALL_TS)), 0) AS 'Metric_1' " & _
"FROM PMBSED_PhoneEvaluations " & _
"GROUP BY Employee_Token_NR "
Set cn = New ADODB.Connection
cn.CommandTimeout = 120
cn.Open sqlconstring
Set rs = New ADODB.Recordset
rs.Open SqlString(i), cn, adOpenStatic, adLockReadOnly
'How I would paste in an excel spreadsheet, how do I block paste in an access database?
'ThisWorkbook.Worksheets("RawData").Cells(RowNumber, 1).CopyFromRecordset rs
RowNumber = RowNumber + rs.RecordCount
rs.Close
cn.Close
End Sub
Thank you for any assistance!
-Robert

How should I use INSERT INTO with a MS Access .mdb database?

This is a work project but I'm having trouble getting my head around using "insert into" for an MS Access DB.
I've tried the following 3 scripts and all return different errors and of course I want my initial problem resolved but I would also appreciate knowing why they are all failing and what's different/best practice. These scripts are all modified ones I've found from searching around:
Script1:
Const adOpenStatic = 3
Const adLockOptimistic = 3
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
objConnection.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source = C:\Users\itsupport\Documents\test.mdb"
objRecordSet.Open _
"INSERT INTO Users" & _
"(Id, Name, " & _
"CertificateName, Password) " & _
"VALUES ('michaelr', 'Michael Raymond', " & _
"'NULL', '888')", _
objConnection, adOpenStatic, _
adLockOptimistic
Error 1:
Syntax error in INSERT INTO statement
Script 2:
Set objConn = CreateObject("ADODB.Connection")
Dim rsData
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\itsupport\Documents\test.mdb'"
objConn.Open strConnection
strInsertSQL = "INSERT INTO Users (iD,Name,CertificateName,Password) VALUES('" & _
michaelr & "','" & Michael Jenkins & "','" & - & "','" & 888 & "', objConnection, adOpenStatic, adLockOptimistic);"
Set rsData = objConn.Execute(strInsertSQL)
Error 2:
Expected end of statement
Script 3:
sql1="INSERT INTO Users VALUES ('michaelr','Michael Jenkins',NULL,'888')"
constring="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Users\itsupport\Documents\test.mdb;
User Id=admin;Password=;"
set con=createobject("adodb.connection")
con.open constring
con.execute sql1
con.close
Error 3:
Unterminated string constant
Script1:
Defining the ad* constants is necessary in plain VBScript (there are no libraries to be referenced)
Non-trivial concatenated strings should be assigned to a variable and displayed for visual inspection
INSERT INTO Users(Id, Name, CertificateName, Password) VALUES ('michaelr', 'Michael Raymond', 'NULL', '888') quotes NULL and uses the reserved word "Password" (see here)
Script 2:
The concatenation 'works' if you double quote michaelr, Michael Jenkins, and - (whatever that means)
String concatenation in VBScript is a mess; unnecessary concatenation should be avoid (as in Script 3)
Script 3:
The syntax error is caused by the bad quoting and missing & _ in the definition of constring (you did it correctly in Script 1)
In general:
A lot of problems of building (and safely using) SQL statements simply vanish if you use parameterized queries
String concatenation in VBScript is a mess; using Arrays and Join, dedicated quote functions, and replacement of placeholders (no variable interpolation/expansion here) will result in better code

VBA Transactions

I'm trying to insert some data into SQL from Excel VBA. The SQL commands are built up over the course of the VBA script, and include the use of some SQL variables.
I'm trying to understand how transactions work in VBA, and whether they will work with what I need to do, I have the code below that will test this, but it does not work. It always gives me an error about "Must define scalar variable #name" so I assume there is an issue here with the scope of the data/transaction. How can I get this simple code to work?
Const stADO As String = "Provider=SQLOLEDB.1;Integrated Security=SSPI;" & _
"Persist Security Info=False;" & _
"Initial Catalog=ImportTest;" & _
"Data Source=localhost\sqlexpress"
Set cn = New ADODB.Connection
With cn
.CursorLocation = adUseClient
.Open stADO
.CommandTimeout = 0
End With
cn.BeginTrans
cn.Execute "set implicit_transactions off"
cn.Execute ("declare #name varchar(100)")
cn.Execute ("set #name='name'")
cn.Execute ("Insert into test (id,name) values (55,#name)")
cn.CommitTrans
cn.Close
Set cn = Nothing
you need to execute all these in 1 batch
cn.Execute "set implicit_transactions off"
cn.Execute ("declare #name varchar(100)")
cn.Execute ("set #name='name'")
cn.Execute ("Insert into test (id,name) values (55,#name)")
built a string and then use 1 cn.Execute
Better yet, use parameterized queries to guard against SQL injection

Unable to connect to SQL2005 using VBScript

Using the connection string below I can connect to a SQL2000 DB but not a SQL2005. I have the code in an ASP file.
Dim connStr, cn, rs, sql
connStr = "Provider=SQLOLEDB;Persist Security Info=True" _
& ";Initial Catalog=mydatabase" _
& ";User ID=dbuser" _
& ";Password=dbpwd" _
& ";Data Source=servername"
sql = "SELECT TOP 1 [Column1] FROM [dbo].[MyTable] order by NEWID()"
Set cn = Server.CreateObject("ADODB.Connection")
cn.Open cn
set rs= server.CreateObject("ADODB.Recordset")
rs.CursorLocation=3
rs.Open sql,cn,3,4
if not rs.EOF then
Response.Write("<b>Column1: " & rs("Column1") & "</b><br />")
end if
set rs.ActiveConnection= nothing
rs.Close
set rs= nothing
if ucase(TypeName(cn)) = "CONNECTION" then
cn.Close
Set cn = Nothing
end if
I have even tired with SQLOLEDB.1
Sql login is enabled on the sql server.
Error: The connection cannot be used to perform this operation. It is either closed or invalid in this context.
Happens on rs.Open sql,cn,3,4
It happens to everybody sometime:
Dim connStr, cn, rs, sql
connStr = "Provider=SQLOLEDB;Persist Security Info=True" _
& ";Initial Catalog=mydatabase" _
& ";User ID=dbuser" _
& ";Password=dbpwd" _
& ";Data Source=servername"
sql = "SELECT TOP 1 [Column1] FROM [dbo].[MyTable] order by NEWID()"
Set cn = Server.CreateObject("ADODB.Connection")
cn.Open connStr
You are calling a variable conn as connection string but you have declared and filled connStr
Change "cn.Open conn" with "cn.Open connStr"
What is the error? SQL Server 2005/8 install with remote connections disabled -- check this support article.
I see, try setting your connString on your Connection object (you use conn instead of connStr). Uee option explicit to avoid these errors.