copy data form sqlserver database to access database and vice versa - ms-access

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.

Related

Extract values from mySQL database into Excel using VBA

I have installed the mySQL server on my computer and created the Database called Sales consisting of one table called Orders. You can also find the table in the SQL fiddle here:
CREATE TABLE Orders (
OrderID INT,
Customer VARCHAR(255),
Revenue VARCHAR(255)
);
INSERT INTO Orders
(OrderID, Customer, Revenue)
VALUES
("1", "Customer A","400"),
("2", "Customer A","200"),
("3", "Customer B","600"),
("4", "Customer C","150"),
("5", "Customer C","800"),
("6", "Customer C","300");
Then I created an Excel file and activated Microsoft ActiveX Data Objects 2.8 Library.
Now I wanted to connect to the Database above and extract data from it using the following VBA script:
Sub ConnectDB()
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=Sales; UID=root; PWD=mypassword; OPTION=3"
Set rs = New ADODB.Recordset
Set rs = conn.Execute("SELECT * FROM sales.orders;")
Sheet1.Range("A1").Value = rs
End Sub
However, when I run this VBA I get runtime error 3704. As far as I can tell this error is probably caused by these lines:
Set rs = New ADODB.Recordset
Set rs = conn.Execute("SELECT * FROM sales.orders;")
because if I delete them the VBA runs without the error.
What do I need to change in my code to extract the Data from the mySQL database?
your connection is not open
try this
Sub ConnectDB()
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=Sales; UID=root; PWD=mypassword; OPTION=3"
conn.open
Set rs = New ADODB.Recordset
Set rs = conn.Execute("SELECT * FROM sales.orders;")
Sheet1.Range("A1").Value = rs
End Sub
Don't use Execute - that is for running a command on the database, not for returning a recordset.
Sub ConnectDB()
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost; DATABASE=Sales; UID=root; PWD=mypassword; OPTION=3"
conn.Open
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM sales.orders;", conn
Sheet1.Range("A1").Value = rs
End Sub
And if your string fields return what looks like garbage, you are going to have to do a little more than that too.
Try it like
Dim oConn As ADODB.Connection
Then
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
Dim str As String
str = "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=XXX.XXX.XXX.XXX replace with your IP address" & ";" & _
"PORT=replace with the port you are using, usually 3306" & ";" & _
"DATABASE=replace with the name of your databese" & ";" & _
"USER=replace with the username you are using to connetc yourself to the databes" & ";" & _
"PASSWORD=replace with password you are using to connect to the databse" & ";" & _
"Option=3"
oConn.Open str
End Sub
And Finally
Sub InsertData()
Dim Rs As ADODB.Recordset
Dim Requete As String
Set Rs = New ADODB.Recordset
Call ConnectDB
Requete = "SELECT * FROM sales.orders;"
Rs.Open Requete, oConnect, adOpenDynamic, adLockOptimistic
End With
oConnect.Close
Set Rs = Nothing
End Sub
Assuming you are using Excel 2000 or newer there is a surprisingly easy way to do this, and to even get the MySQL column names.
Public Sub insert_data()
Dim dbConn As New ADODB.Connection, rs As New ADODB.Recordset, sql As String
Dim ws As New Excel.Worksheet, cCtr As Long, numFields As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
dbConn.ConnectionString = "[put your connection string here]"
dbConn.Open
sql = "SELECT * FROM sales.orders;"
Set rs = New ADODB.Recordset
Set rs = dbConn.Execute(sql, , adCmdText)
With ws
' Get the number of columns:
numFields = rs.Fields.Count
' Put the column names into the first row of your worksheet:
For cCtr = 1 To numFields
.Cells(1, cCtr).Value = rs.Fields(cCtr - 1).name
Next cCtr
' Put all the recordset data into your worksheet,
' starting from the worksheet's second row:
.Cells(2, 1).CopyFromRecordset rs
End With
dbConn.Close
End Sub

Connection to Access 2013 database with VB6

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

How to delete all records of a table in MS Access using VB6 ADO

I want to delete all records of a table in MS Access using VB.6 code.
Actually I'm going to reset my database with it, by that I mean to have NO records anymore.
How can I do that?
I have done it.
On Error Resume Next
Dim cnn As New ADODB.Connection
cnn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\DB.mdb"
cnn.Open
cnn.Execute "delete * from LogTBL"
cnn.Close
Here is code that will delete all records in all tables of the Access database you are connected to. HOWEVER!! If you have built relationships between tables and have not specified 'Cascade Delete', then you can't delete the 'owner' table until deleting from the 'member' table. One way around that is to add an error trap so that you check that condition, then ignore (Resume Next). But then you would need to repeat running this code until no errors. You need to set your connection string (see comment in code)!!
Function Delete_All_Data()
Dim cnLocalData As ADODB.Connection
Dim catLocal As ADOX.Catalog
Dim tdf As ADOX.Table
Dim strSQL As String
Dim strTableName As String
Set cnLocalData = New ADODB.Connection
MsgBox " Add code to connect to your database either using Connection cnLocalData or your own and change this code!!!"
Set catLocal = New ADOX.Catalog
catLocal.ActiveConnection = cnLocalData
For Each tdf In catLocal.Tables
If UCase(tdf.Type) = "TABLE" And UCase(Left(tdf.Name, 4)) <> "MSYS" Then
if tdf.Name <> "INFOTBL" Then
strTableName = tdf.Name
strSQL = "delete * from [" & strTableName & "];"
cnLocalData.Execute strSQL
End If
End If
Next tdf
Set tdf = Nothing
Set catLocal = Nothing
cnLocalData.Close
Set cnLocalData = Nothing
End Function

how to create custom function in excel to grab mysql data?

We need to create a custom formula for users to pull data from our mysql database. After the user is authenticated, they would type in a formula in excel (something like '=retrievemybirthday("Frank Dodge")'. How do we go about doing that? We're not new to programming, just new to programming w/ Excel. Are there any tutorials on this? We've looked but can find anything.
thanks!
1) you need an ODBC driver configured for your MySQL db.
2) figure out the SQL code you need for this function, something like
select birthdate
from YourTable
Where membername=?
You will use this code in your function
3) In your function, you will need the correct Connection String. Check a site like http://www.connectionstrings.com/
4) Here's an example of a function, using ActiveX Data Objects (you need a reference set in Tools > References in the VB Editor)
Function GetNomen(sPN As String) As String
'SkipVought/2006 Mar 7
'--------------------------------------------------
' Access: DWPROD.FRH_MRP.READ
'--------------------------------------------------
':this function returns nomenclature for a given part number
'--------------------------------------------------
'2011-9-26 Converted to Parameter Query
'--------------------------------------------------
Dim sConn As String, sSQL As String, sServer As String
Dim rst As ADODB.Recordset, cnn As ADODB.Connection, cmd As ADODB.Command
Set rst = New ADODB.Recordset
Set cnn = New ADODB.Connection
Set cmd = New ADODB.Command
sServer = "dwprod"
cnn.Open "Driver={Microsoft ODBC for Oracle};" & _
"Server=" & sServer & ";" & _
"Uid=/;" & _
"Pwd="
sSQL = "SELECT PM.Nomen_201 "
sSQL = sSQL & "FROM FRH_MRP.PSK02101 PM "
sSQL = sSQL & "WHERE PM.PARTNO_201 =?"
Debug.Print sSQL
With cmd
.CommandText = sSQL
.CommandType = adCmdText
.Prepared = True
.Parameters.Append .CreateParameter( _
Name:="PARTNO_201", _
Type:=adChar, _
Direction:=adParamInput, _
Size:=16, _
Value:=sPN)
.ActiveConnection = cnn
Set rst = .Execute
End With
rst.MoveFirst
If Err.Number = 0 Then
GetNomen = rst("NOMEN_201")
Else
GetNomen = ""
End If
rst.Close
cnn.Close
Set cmd = Nothing
Set rst = Nothing
Set cnn = Nothing
End Function
You can run this function on the sheet as requested.

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