Whenever I attempt to query a file using Python script, I receive the following error
pyodbc.InterfaceError: ('IM002', u'[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
Image of Error Message
My code is as followings:
conn = pyodbc.connect ("DRIVER={ODBCDataFile [Microsoft Access Driver
(*.mdb, *.accdb)]};DBQ=C:\Users\jmtr\Documents\IRST_old.accdb;")
cur = conn.cursor()
cur.execute("SELECT Name, CAI, Email, SSPLocation, BUNUM from Tbl_SSP")
My Access database is "Microsoft Access 2016 32-bit". I am also using "32-bit" python 2.7.13 and 32-bit PYODBC. And, I have 32-bit drivers set-up in the ODBC Data Source Administrator:
Image of ODBC 32-bit
I don't understand why I am still receiving this error message?
Connection string is incorrect. There is no ODBCDataFile keyword with brackets [...]. Simply remove them and assign DRIVER to installed ODBC driver as your screenshot shows:
conn = pyodbc.connect("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};" + \
"DBQ=C:\\Users\\jmtr\\Documents\\IRST_old.accdb;")
I think you misspelled ODBCDataFile instead of ODBCFile.
But in python the character \ is the escape character in the strings. You need to append the prefix r"DRIVER..." to force raw strings, so without missinterpreting the escape character.
First download and install Microsoft Access Database Engine 2010 Redistributable if you haven’t.
Then you should install pyodbc module.
Now you can connect to access database :
ConFileName=(r'c:\mydb\myaccess.mdb')
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + ConFileName + ';')
cursor = conn.cursor()
To select from any table in the database please use this simple code :
ConFileName=(r'c:\mydb\myaccess.mdb')
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + ConFileName + ';')
cursor = conn.cursor()
cursor.execute('select * from table1')
for row in cursor.fetchall():
Table1Array.append((row[0],row[1],row[2])
print(str(len(Table1Array))+" records in Table1 loaded successfully.")
You can follow this link to get more information about working with MS Access by Pyton :
https://elvand.com/python-and-ms-access/
Related
im trying to make a connection to an as400 with db2 using pyodbc and the ibm db2 odbc driver.
import pyodbc
connection = pyodbc.connect(
driver='{IBM DB2 ODBC DRIVER}',
system='192.168.1.100',
uid='user',
pwd='pass')
c1 = connection.cursor()
#this is meaningless sql, i just want the connection
c1.execute('select * from libname.filename')
for row in c1:
print (row)
Running this gives me this error
python pydata.py
Traceback (most recent call last):
File "C:\Users\tca\Desktop\ScriptingSTuff\pydata.py", line 3, in <module>
connection = pyodbc.connect(
pyodbc.OperationalError: ('08001', '[08001] [IBM][CLI Driver] SQL1013N The database alias name or database name "" could not be found. SQLSTATE=42705\r\n (-1013) (SQLDriverConnect)')
Any ideas?
This is all under win10
EDIT:
Adding this "database='s10c38ft',"
import pyodbc
connection = pyodbc.connect(
driver='{IBM DB2 ODBC DRIVER}',
system='192.168.1.100,8471',
database='s10c38ft',
uid='user',
pwd='pass')
c1 = connection.cursor()
c1.execute('select * from libname.filename')
for row in c1:
print (row)
Makes it hang on a blinking cursor, I cant even CTRL+C to end it, I have to close cmd.
The proper driver name should be IBM i Access ODBC Driver (but see notes below). Other than that, your first example was correct:
connection = pyodbc.connect(
driver='{IBM i Access ODBC Driver}',
system='192.168.1.100',
uid='user',
pwd='pass')
If that doesn't work, there are two main possibilities:
You are using an old ODBC driver. This would happen if you are using the old iSeries Access (in which case the driver name is iSeries Access ODBC Driver) or even older Client Access (driver name Client Access ODBC Driver (32-bit)). If you choose the appropriate name for your driver, it will work.
You are using an ODBC driver that is not for IBM i. The most commonly used member of the Db2 family is Db2 for LUW (Linux, Unix, Windows), but there are others. None of these will work for you.
You can find out the list of exact ODBC driver names you have installed by calling pyodbc.drivers(). If you don't have any of the ones I mentioned above by name, then you don't have the right driver. The ODBC driver you want is the one described here.
I am now facing a difficulty connecting VIEW table in mdb file using pyodbc.
Current code is as follows:
(Previous Provider: Microsoft.Jet.OLEDB.4.0)
import pyodbc
pyodbc.pooling = False
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=C:***.mdb;'
)
cnxn = pyodbc.connect(conn_str)
crsr = cnxn.cursor()
for table_info in crsr.tables(tableType='TABLE'):
print(table_info.table_name)
strSQL = "SELECT A,B FROM tableC WHERE ** ORDER BY B"
crsr.execute(strSQL)
for row in crsr.fetchall():
print(row)
When it works, for table_info in crsr.tables(tableType='TABLE'): seems to have no issue.
This is because print(table_info.table_name) displays several table names.
However, when crsr.execute(strSQL) is done, exeption error has raised and following message
('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver] ODBC--connection to 'VIEW' failed. (-2001) (SQLExecDirectW)")
is shown.
It would be appreciated to instruct me how to overcome this issue.
Thanks.
Using Python, I'm trying to read a table from SQL Server and then insert the data into a table in Access. The best way I've found to do this is using the pandas dataframe. I wrote up a program that reads a SQL Server table into a dataframe like so:
dataframe = pandas.read_sql(selectSql, srcConn)
And it works great on a ~209MB table. When I try it on a ~1,116MB table it throws an exception with no description. I'm guessing it has to do with the size of the table it's reading in (it would be nice if it said that). I know Access can only hold 2GB but there is plenty of room left in it and it doesn't even get to the part where it writes to Access before throwing the error.
Is there any way to fix this for larger tables? Is there a better way I should be copying tables from SQL Server 2008 R2 to Access 2016 using Python? I have 16GB of RAM on Win10 64-bit so that shouldn't be a problem. I've tried 32-bit Python 3.7 and 64-bit Python 3.6 to no avail. I tried SSIS first but it crashes my entire Visual Studio whenever I try to open a package with a connection to Access.
UPDATE:
I followed Gord's advice below and now my code looks like this:
access_cnxn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=' + access_db + ';'
)
sqls_cnxn_str = (
r'DRIVER=ODBC Driver 13 for SQL Server;'
r'SERVER=' + sqls_server + ';'
r'DATABASE=' + sqls_db + ';'
r'UID=' + sqls_username + ';'
r'PWD=' + sqls_password + ';'
)
This connection works by itself:
sqls_cnxn = pyodbc.connect(sqls_cnxn_str)
And this connection works by itself:
pyodbc.pooling = False
access_cnxn = pyodbc.connect(access_cnxn_str, autocommit = True)
But this is throwing an error:
access_cnxn.execute(f"SELECT * INTO {access_table} FROM [ODBC;{sqls_cnxn_str}].{sqls_table}")
The error thrown:
Message=('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver]
ODBC--connection to 'ODBC Driver 13 for SQL ServerSERVERNAME' failed.
(-2001) (SQLExecDirectW)")
Source=C:\Users\bruescm\source\repos\DB_Test\DB_Test\SyncAllTests.py
StackTrace: File
"C:\Users\bruescm\source\repos\DB_Test\DB_Test\SyncAllTests.py", line
57, in sync_table
dest_cnxn.execute(f"SELECT * INTO {access_table} FROM [ODBC;{sqls_cnxn_str}].{sqls_table}") File
"C:\Users\bruescm\source\repos\DB_Test\DB_Test\SyncAllTests.py", line
121, in main
sync_table('', sqls_table, get_access_cnxn(), access_table) File "C:\Users\bruescm\source\repos\DB_Test\DB_Test\SyncAllTests.py", line
124, in
main()
SERVERNAME in the error is the name of the server on which SQL Server resides. Not sure why it jammed it up against the driver name in the error.
Any ideas?
UPDATE 2:
It turns out my Access is 32-bit. This still doesn't explain why it won't connect as I was originally using Python 3.7 32-bit.
Thanks.
I was able to get the Access Database Engine to pull a table from SQL Server and create a copy in the Access database by simply doing
pyodbc.pooling = False # required
cnxn = pyodbc.connect("DSN=myAccessDb", autocommit=True)
cnxn.execute("SELECT * INTO access_tbl FROM [ODBC;DSN=SQLmyDb].sql_server_tbl")
where SQLmyDb is the ODBC DSN for my SQL Server instance.
Update
Just tested to confirm that DSN-less connection strings also work:
pyodbc.pooling = False # required
access_cnxn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=C:\__tmp\test.accdb;'
)
cnxn = pyodbc.connect(access_cnxn_str, autocommit=True)
sql_cnxn_str = (
r'DRIVER=ODBC Driver 17 for SQL Server;'
r'SERVER=(local)\SQLEXPRESS;'
r'DATABASE=myDb;'
r'Trusted_Connection=Yes;'
)
cnxn.execute(f"SELECT * INTO access_tbl FROM [ODBC;{sql_cnxn_str}].sql_server_tbl")
How can I access my Microsoft Access 2010 database (accdb) with pyodbc?
Before, I used an mdb Database, which worked fine with the connection string being:
ODBC_CONN_STR = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=%s;' % ACCESS_DATABASE_FILE
Now I use:
import pyodbc
ACCESS_DATABASE_FILE = "PSA_TEST.accdb"
ODBC_CONN_STR = 'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;' % ACCESS_DATABASE_FILE
conn = pyodbc.connect(ODBC_CONN_STR)
The error I get is:
pyodbc.Error: ('HY000', '[HY000] [Microsoft][ODBC-Treiber für Microsoft Access] Kein zulässiger Dateiname. (-1044) (SQLDriverConnect)')
Which translates to "the filename is not acceptable".
I found a related question, but the answer does not work for me (Connecting to MS Access 2007 (.accdb) database using pyodbc). I use 32 bit python according to the output of:
python -c 'import struct; print struct.calcsize("P") * 8'
and MS Access 32 bit.
[EDIT]
Just in case, I check with os.path.isfile(ACCESS_DATABASE_FILE) that the file actually exists
the file can be opened with Access
opening the previous mdb file with the new connection string gives the same error message, which afaik is not the expected behavior
Ok, sorry to answer my own question, but by playing around, I learned that you need to specify the absolute path name if you use the second connection string:
ACCESS_DATABASE_FILE = 'C:\\path\\to\\PSA_TEST.accdb'
ODBC_CONN_STR = 'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;' % ACCESS_DATABASE_FILE
Then it even works with the accdb file, as well as with the mdb file as expected.
I'm trying to read data stored in a ms access database that generated by a piece of software Hy Tek Meet Manager
import pyodbc
filename = 'db.mdb'
connection = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+filename)
cursor = conn.cursor()
When I run this code I get the error:
pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnectW)')
All other searches for this error have led to dead ends. Any suggestions as to why this is happening?
Based on one of your comments it sounds like you are using the EasySoft MS Access ODBC drivers. Referencing their support page, I would guess the following is what you want to use for your connection string:
import pyodbc
filename = 'db.mdb'
connection = pyodbc.connect('DRIVER={Easysoft ODBC-ACCESS}; MDBFILE='+filename)
cursor = conn.cursor()