Connection to Access 2013 database with VB6 - ms-access

I am trying to connect to an Access database 2013 (.accdb) from VB6, and keep getting errors. My code is as follows:
Dim db_file As String
Dim statement As String
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
' Get the data.
db_file = App.Path
If Right$(db_file, 1) <> "\" Then db_file = db_file & "\"
db_file = db_file & "FluidFlo.accdb"
' Open a connection.
Set conn = New ADODB.Connection
conn.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & db_file & ";" & "Persist Security Info=False"
conn.Open '(PROBLEM IS HERE)
' Select the data.
statement = "SELECT strEmpName FROM tblEmployees ORDER BY strEmpName"
' Get the records.
Set rs = conn.Execute(statement, , adCmdText)
' Load the results into the ComboBox
Do Until rs.EOF
cboUsername.AddItem rs!strEmpName
rs.MoveNext
Loop
' Close the recordset and connection.
rs.Close
conn.Close
I am trying to load a table in to a combobox in the program, and assuming my connection string is having an error. I changed the Provider=Microsoft.ACE.OLEDB.12.0; to Provider=Microsoft.ACE.OLEDB.15.0; and still no luck. Keep getting an error.
Does anyone have an idea of how to connect to an .accdb database, whether SQL commands or any? Thanks in advance...(pulling my hair out...)

Related

copy data form sqlserver database to access database and vice versa

I have built a program by ms access as a front and save DATA IN sql server database. Also I have some local table in my program.
My program is connected to sql server by connection string and i can read, write, delete and update data.Sometimes I need to copy result of a query to my local table into access and sometimes I want to append one of my access table to sql table
I have written a connection and tried to executed it like this:
Function CopyData()
Dim cn as ADODB.Connection
Dim strServer, strDatabase, strUsername, strPassword As String
Dim strConnectionString As String
strServer = "10.25.2.120"
strDatabase = "dbKala"
strUsername = "javid"
strPassword = "1234"
strConnectionString = "Provider=SQLOLEDB;Data Source=" & strServer & ";Initial Catalog=" & strDatabase & ";User ID=" & strUsername & ";Password=" & strPassword & ";"
Set cn = New ADODB.Connection
cn.ConnectionString = strConnectionString
cn.CommandTimeout = 0
cn.Open
cn.Execute "INSERT INTO GetTelServer Select * FROM dbo.telefone"
End Function
but data isn't copied from sql to access and show me a message about invalid object my access table
I need to help me how to copy a query from sql to access table and vice verse
This task would be a lot easier with linked DAO.Tables, but that needs proper ODBC-Driver for SQL-Server.
If Ms-Access and SQL-Servers bitness match (x64) you can try using OPENROWSET on SQL-Server to access Ms-Access tables from there.
E.g
INSERT INTO SqlServerTable (SqlServerField) SELECT AccessField FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'C:\Program Files\Microsoft Office\OFFICE11\SAMPLES\Northwind.mdb';
'admin';'',AccessTable);
If bitness doesn't match, you have to create 2 different connections and use recordsets (or Action-Query for insert)
One rs is to select the data, second is for inserts:
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim cn2 As ADODB.Connection, rs2 As ADODB.Recordset
Set cn = New ADODB.Connection
cn.Open "Provider=SQLNCLI11;Server=server;Database=db;Trusted_Connection=yes;"
Set cn2 = New ADODB.Connection
cn2.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Path\To\AccessDb;"
Set rs = cn.Execute("SELECT SqlServerField FROM SQLSERVERTable")
Set rs2 = cn2.Execute("SELECT AccessField FROM AccessTable")
Do Until rs2.Eof
rs.AddNew
rs.Fields("SqlServerField").Value = rs2.Fields("AccessField").Value
rs.Update
rs2.MoveNext
Loop
rs.Close
rs2.Close
cn.Close
cn2.Close
Of course the fields data-types have to be compatible.

Connect to an SQL database from EXCEL

I have gone through a few tutorials already and my connection keeps failing, I have tried a lot of different ways of connecting.
I have a connection to mySQL through the mySQL workbench. I am using the IP address and the Port number and then my credentials to login. This works well and I am able to do the queries I need.
I am now trying to access this database through Excel, preferably through VBA. I tried to create a new connection but nothing I do seems to work. I am not sure what to put into my strConn string.
I am currently using:
Options Explicit
Private Sub CommandButton2_Click()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
Set cn = New ADODB.Connection
strConn = "DRIVER={MySQL ODBC 5.3.7 Driver};" & _
"SERVER=XXX.XXX.X.X;" & _
"PORT=3306" & _
"DATABASE=cahier_de_lab;" & _
"UID=xxx;" & _
"PWD=xxx;" & _
"Option=3"
cn.Open strConn
' Find out if the attempt to connect worked.
If cn.State = adStateOpen Then
MsgBox "Welcome to Pubs!"
Else
MsgBox "Sorry. No Pubs today."
End If
' Close the connection.
cn.Close
End Sub
Thanks for your help!
Export from Excel to SQL Server.
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Excel-PC\SQLEXPRESS"
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=Excel-PC\SQLEXPRESS;DATABASE=Northwind;Trusted_Connection=Yes"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
OR . . . .
Import from SQL Server into Excel . . . . .
Sub Create_Connectionstring()
Dim objDL As MSDASC.DataLinks
Dim cnt As ADODB.Connection
Dim stConnect As String 'Instantiate the objects.
Set objDL = New MSDASC.DataLinks
Set cnt = New ADODB.Connection
On Error GoTo Error_Handling 'Show the Data-link wizard
stConnect = objDL.PromptNew 'Test the connection.
cnt.Open stConnect 'Print the string to the VBE Immediate Window.
Debug.Print stConnect 'Release the objects from memory.
exitHere:
cnt.Close
Set cnt = Nothing
Set objDL = Nothing
Exit Sub
Error_Handling: 'If the user cancel the operation.
If Err.Number = 91 Then
Resume exitHere
End If
End Sub

How do I setup an ADODB connection to SQL Server 2008 in Microsoft Access 2010?

I just installed SQL Server 2008 on my laptop. I also have Microsoft Access 2010 installed. Using VBA, I am trying to create an ADODB connection to my own database on SQL Server but I'm having trouble finding the right line of code:
When I use this below, it doesn't work.
The name of my computer is LAPTOPX and the database is HomeSQL.
I am sure it's super easy but since I'm just starting out I can't seem to find the right way to ask the question.
Thanks!
Dim DBCONT As Object
Set DBCONT = CreateObject("ADODB.Connection")
Dim strDbPath As String
strDbPath = "LAPTOPX/HomeSQL"
Dim sConn As String
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source =" & strDbPath & ";" & _
"Jet OLEDB:Engine Type=5;" & _
"Persist Security Info=False;"
DBCONT.Open sConn
First, you need to make sure SQL Native Client is instaled. Reference
SQL Server 2008
Standard security
Provider=SQLNCLI10;Server=myServerAddress;Database=myDataBase;Uid=myUsername;
Pwd=myPassword;
Trusted connection
Provider=SQLNCLI10;Server=myServerAddress;Database=myDataBase;
Trusted_Connection=yes;
Connecting to an SQL Server instance
The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.
Provider=SQLNCLI10;Server=myServerName\theInstanceName;Database=myDataBase;
Trusted_Connection=yes;
Source
Dim conn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim sConnString As String
Dim recordsAffected as Long
'Create connection string
sConnString = "Provider=sqloledb; Server=LAPTOPX; Database=HomeSQL; Trusted_Connection=True;"
'Open connection and execute
conn.Open sConnString
'Do your query
With cmd
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = "Select ...;"
.Execute recordsAffected 'Includes a return parameter to capture the number of records affected
End With
Debug.Print recordsAffected 'Check whether any records were inserted
'Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set cmd = Nothing
Set conn = Nothing
This connetion string works under Excel VBA. In MsAccess also should.
dbName = "test" 'your database name
dbFilePath = "C:\db.mdf" 'your path to db file
connStr = "Driver={SQL Server native Client 11.0};" & _
"Server=(LocalDB)\v11.0;" & _
"AttachDBFileName=" & dbFilePath & ";" & _
"Database=" & dbName & ";" & _
"Trusted_Connection=Yes"
Full solution: http://straightitsolutions.blogspot.com/2014/12/how-to-connect-to-sql-server-local.html

Problem with VBA script reading from MySql database

I am having some trouble with a vba script in Excel which should be
reading from a MySql database. The SQL query should only return one
record but actually returns an empty resultset. The generated statement works fine when run through phpMyAdmin.
Here is my code:
Function getClientId(emailAddress As String)
Dim rs As ADODB.Recordset
Dim sql As String
ConnectDB
Set rs = New ADODB.Recordset
sql = "SELECT client_id FROM clients WHERE email_address = '" & emailAddress & "' LIMIT 1"
Debug.Print sql
rs.Open sql, oConn
Debug.Print rs.RecordCount
If (rs.RecordCount = -1) Then
getClientId = Null
Else
getClientId = rs(0)
End If
rs.Close
End Function
EDIT: My database connect function.
Function ConnectDB()
On Error GoTo ErrHandler
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & _
"DATABASE=mydb;" & _
"USER=user;" & _
"PASSWORD=password;" & _
"Option=3"
'Debug.Print oConn
Exit Function
ErrHandler:
MsgBox Err.Description, vbCritical, Err.Source
End Function
The ConnectDB function is connecting ok as I am running other scripts
with it. If anyone can see what I am doing wrong then any help would
be appreciated.
Many thanks in advance.
Garry
MyODBC does not properly provide the RecordCount-Attribute.
Re: Problem with RecordCount with ASP & MySQL
rs.recordcount = -1 with myODBC
Re: ADO Connection RecordCount
So, if you really need the RecordCount, set CursorLocation Property to adUseClient.
If not, just iterate through the RecordSet like this:
Do While Not rs.EOF
'...do your magic
rs.MoveNext
Loop
Use " (double quote) instead of ' (single quote), because you are querying through the ODBC driver.
This could be problem of driver you have selected. My suggestion is (and I may be wrong) - if you are connecting via ODBC it could have different set of commands.

How to save an ADO recordset into a new local table in Access 2003?

I'm trying to import tables from a FoxPro 9.0 database into Access 2003. So far, from Google searches and many trials, the only way for me to connect to the tables is through an OLE DB connection programatically. I have set up 3 ODBC connections with different configurations but none of them work: I get "unspecified errors" that I can't find any information on.
With OLE DB I can succesfully connect to the FoxPro database, and import tables in ADO recordsets. The problem is that I can't save the recordset into new table in the local database using SQL. The ADO recordsets behave differently than tables, so I can't query them. The code below gives me a "type mismatch" error at DoCmd.RunCommand ("select * from " & rst & " INTO newClients").
Sub newAdoConn()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim strSQL As String
Dim decision As Integer
Set cnn = New ADODB.Connection
cnn.ConnectionString = "Provider=vfpoledb;" & _
"Data Source=s:\jobinfo\data\jobinfo.dbc;" & _
"Mode=ReadWrite|Share Deny None;" & _
"Collating Sequence=MACHINE;" & _
"Password=''"
strSQL = "Select * from Jobs"
cnn.Open
Set rst = cnn.Execute("Select * from clients")
If rst.EOF = False Then
Do While Not rst.EOF
decision = MsgBox(rst.Fields!ID & " " & rst.Fields!fname & " " & rst.Fields!lname & vbCrLf & vbCrLf & "Continue?", vbYesNo)
If decision = vbYes Then
rst.MoveNext
Else
Exit Do
End If
Loop
End If
DoCmd.RunCommand ("select * from " & rst & " INTO newClients")
rst.Close
Set rst = Nothing
cnn.Close
Set cnn = Nothing
End Sub
I finally worked out a decent solution. It involves saving the ado recordset from memory to an excel file using the copyFromRecordset function, and then linking the file programmatically to a table in excel using the TransferSpreadsheet()...
Sub saveToExcel()
Dim cnn As ADODB.Connection
'declare variables
Dim rs As ADODB.Recordset
Dim strSQL As String
Dim decision As Integer
Dim colIndex As Integer
' Dim fso As New FileSystemObject
' Dim aFile As File
'set up connection to foxpro database
Set cnn = New ADODB.Connection
cnn.ConnectionString = "Provider=vfpoledb;" & _
"Data Source=s:\jobinfo\data\jobinfo.dbc;" & _
"Mode=ReadWrite|Share Deny None;" & _
"Collating Sequence=MACHINE;" & _
"Password=''"
cnn.Open
Set rs = cnn.Execute("Select * from clients")
'Create a new workbook in Excel
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Add
Set oSheet = oBook.Worksheets(1)
oSheet.Name = "clients"
' Copy the column headers to the destination worksheet
For colIndex = 0 To rs.Fields.Count - 1
oSheet.Cells(1, colIndex + 1).Value = rs.Fields(colIndex).Name
Next
'Transfer the data to Excel
oSheet.Range("A2").CopyFromRecordset rs
' Format the sheet bold and auto width of columns
oSheet.Rows(1).Font.Bold = True
oSheet.UsedRange.Columns.AutoFit
'delete file if it exists - enable scripting runtime model for this to run
'If (fso.FileExists("C:\Documents and Settings\user\Desktop\clients.xls")) Then
' aFile = fso.GetFile("C:\Documents and Settings\user\Desktop\clients.xls")
' aFile.Delete
'End If
'Save the Workbook and Quit Excel
oBook.SaveAs "C:\Documents and Settings\user\Desktop\clients.xls"
oExcel.Quit
'Close the connection
rs.Close
cnn.Close
MsgBox ("Exporting Clients Done")
'link table to excel file
DoCmd.TransferSpreadsheet acLink, acSpreadsheetTypeExcel5, "clientsTest", "C:\Documents and Settings\user\Desktop\clients.xls", True
End Sub
What you will have to do is open the FoxPro table as a recordset and open the local table as another recordset. You can then loop through the FoxPro recordset and do something like this
Do until FoxProRst.EOF
LocatRst.AddNew
LocalRst!SomeField1=FoxProRst!SomeField1
LocalRst!SomeField2=FoxProRst!SomeField2
LocalRst!SomeField3=FoxProRst!SomeField3
LocalRst.Update
FoxProRst.MoveNext
Loop
It might not be the quickest way but it will work
Let me just sketch another approach with SQL queries, that could simplify:
'...
'not required for first time test:
'cnn.Execute("DROP TABLE MyNewTable")
'...
'create the new table in the destination Access database
cnn.Execute("CREATE TABLE MyNewTable (MyField1 int, MyField2 VARCHAR(20), MyField3 Int)")
'insert data in the new table from a select query to the original table
Dim sSQL as string, MyOriginalDBPath as String
sSQL = "INSERT INTO MyNewTable (MyField1, MyField2, MyField3) SELECT OriginalField1, OriginalField2, OriginalField3 FROM [" & MyOriginalDBPath & ";PWD=123].clients"
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open sSQL, cnn, adOpenForwardOnly, adLockReadOnly, adCmdText
'...
Note: this 'draft' idea assumes that the connection string is made to the Access database and the connection to the original database would be inside the SQL string, but i have not idea about the correct sintaxis. I have only tested this approach with different access databases.
Note that this is for Access: ...[" & MyOriginalDBPath & ";PWD=123]...
The Jet database engine can reference external databases in SQL statements by using a special syntax that has three different formats:
[Full path to Microsoft Access database].[Table Name]
[ISAM Name;ISAM Connection String].[Table Name]
[ODBC;ODBC Connection String].[Table Name]
...
You can use an ODBC Data Source Name (DSN) or a DSN-less connection string:
DSN: [odbc;DSN=;UID=;PWD=]
DSN-less: [odbc;Driver={SQL Server};Server=;Database=;
UID=;PWD=]
Some references:
Querying data by joining two tables in two database on different servers
C# - Join tables from two different databases using different ODBC drivers
Why not use ODBC to link to the table? http://support.microsoft.com/kb/225861