Using an Access database (.mdb) with Python on Ubuntu [duplicate] - python

This question already has answers here:
Working with an Access database in Python on non-Windows platform (Linux or Mac)
(4 answers)
Closed 6 years ago.
I'm trying to use pyodbc to access a .mdb on Ubuntu. I've based my progress so far on this link
Query crashes MS Access
I have installed pyodbc, unixodbc, and unixodbc-dev
My code looks like this:
import csv
import pyodbc
MDB = 'URY.mdb'
DRV ='Microsoft Access Driver (*.mdb)'
PWD = 'pass'
conn = pyodbc.connect('DRIVER=%s;DBQ=%s;PWD=%s' % (DRV,MDB,PWD))
curs = conn.cursor()
When I run it, I receive this error message:
Traceback (most recent call last):
File "mdbscraper.py", line 8, in <module>
conn = pyodbc.connect('DRIVER=%s;DBQ=%s;PWD=%s' % (DRV,MDB,PWD))
pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)')
Does anyone have any ideas? Any help would be very much appreciated
Thank you!

From what I know this driver "Microsoft Access Driver (*.mdb)" is only available on a Microsoft host, since you are on ubuntu, it won't work.

import pyodbc
DBfile = '/data/MSAccess/Music_Library.mdb'
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+DBfile)
cursor = conn.cursor()
SQL = 'SELECT Artist, AlbumName FROM RecordCollection ORDER BY Year;'
for row in cursor.execute(SQL): # cursors are iterable
print row.Artist, row.AlbumName
cursor.close()
conn.close()
There is The Official Example .. of use ...

Related

I'm trying to connect to a progress database with OpenEdge 10.1B Driver using python's pyodbc library but i get error 126 specified module not found

I can't provide the exact error but i will try to translate:
Traceback (most recent call last):
File "\\dellserver\uyumsoft$\dlc10\bin\odbctest.py", line 4, in <module>
cnxn = pyodbc.connect("DRIVER={Progress OpenEdge 10.1B Driver};"
pyodbc.InterfaceError: (Specified driver could not be loaded due to system error 126: The specified module could not be found.(Progress OpenEdge 10.1B Driver, U:\\dlc10\\bin\\pgoe1022.dll) (160) (SQLDriverConnect)')
here is my code
import pyodbc
cnxn = pyodbc.connect("DRIVER={Progress OpenEdge 10.1B Driver};HostName=dellserver;Database=uyum2008;server=192.168.0.253;LogonID=*****;PASSWORD=******")
I also get almost exactly the same error when i try to access the database using 64 bit odbc driver
but there is no error when i use the 32 bit driver...

python - java.lang.Exception: Class oracle.jdbc.driver.OracleDriver not found

Being a newbie to python, trying to write a python code to connect to the oracle database without using any Instant client. i'm using jaydebeapi and jpype as suggested in some other threads in this forum. After lot of hurdles, i now got stuck at this error. here is the code.
import jaydebeapi
import jpype
try:
con = jaydebeapi.connect('oracle.jdbc.driver.OracleDriver', ['windb19.ams.com', 'AA3112D1OS', 'advantage', 'C:\Tools\ojdbc8.jar'])
cur = con.cursor()
cur.execute('select * from r_sc_user_info')
except Exception as e:
print e
and the error i'm receiving is as below
C:\Python27\python.exe C:/Project/Robot_Framework/SampleProject/CustomLibraries/DBLibrary.py
java.lang.Exception: Class oracle.jdbc.driver.OracleDriver not found
Process finished with exit code 0
As I couldn't modify anything in the Environment variables, as per the policy, I had to modify the code as below to make it work. I had to keep the ojdbc8.jar in the same path as that of this python file and add following lines of code.
jar=os.getcwd()+'\ojdbc8.jar'
args = '-Djava.class.path=%s' % jar
jvm_path = jpype.getDefaultJVMPath()
jpype.startJVM(jvm_path, args)
try:
con = jaydebeapi.connect("oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:#HOSTNAME",["USERID", "PASSWORD"], jar)

I get NotImplementedError when trying to do a prepared statement with mysql python connector

I want to use prepared statements to insert data into a MySQL DB (version 5.7) using python, but I keep getting a NotImplementedError.
I'm following the documentation here: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorprepared.html
Using Python 2.7 and version 8.0.11 of mysql-connector-python library:
pip show mysql-connector-python
---
Metadata-Version: 2.1
Name: mysql-connector-python
Version: 8.0.11
Summary: MySQL driver written in Python
Home-page: http://dev.mysql.com/doc/connector-python/en/index.html
This is a cleaned version (no specific hostname, username, password, columns, or tables) of the python script I'm running:
import mysql.connector
from mysql.connector.cursor import MySQLCursorPrepared
connection = mysql.connector.connect(user=username, password=password,
host='sql_server_host',
database='dbname')
print('Connected! getting cursor')
cursor = connection.cursor(cursor_class=MySQLCursorPrepared)
select = "SELECT * FROM table_name WHERE column1 = ?"
param = 'param1'
print('Executing statement')
cursor.execute(select, (param,))
rows = cursor.fetchall()
for row in rows:
value = row.column1
print('value: '+ value)
I get this error when I run this:
Traceback (most recent call last):
File "test.py", line 18, in <module>
cursor.execute(select, (param,))
File "/home/user/.local/lib/python2.7/site-packages/mysql/connector/cursor.py", line 1186, in execute
self._prepared = self._connection.cmd_stmt_prepare(operation)
File "/home/user/.local/lib/python2.7/site-packages/mysql/connector/abstracts.py", line 969, in cmd_stmt_prepare
raise NotImplementedError
NotImplementedError
CEXT will be enabled by default if you have it, and prepared statements are not supported in CEXT at the time of writing.
You can disable the use of CEXT when you connect by adding the keyword argument use_pure=True as follows:
connection = mysql.connector.connect(user=username, password=password,
host='sql_server_host',
database='dbname',
use_pure=True)
Support for prepared statements in CEXT will be included in the upcoming mysql-connector-python 8.0.17 release (according to the MySQL bug report). So once that is available, upgrade to at least 8.0.17 to solve this without needing use_pure=True.

AttributeError: module 'odbc' has no attribute 'connect' - python with pydev

I am very new to python and I just can't seem to find an answer to this error. When I run the code below I get the error
AttributeError: module 'odbc' has no attribute 'connect'
However, the error only shows in eclipse. There's no problem if I run it via command line. I am running python 3.5. What am I doing wrong?
try:
import pyodbc
except ImportError:
import odbc as pyodbc
# Specifying the ODBC driver, server name, database, etc. directly
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=PXLstr,17;DATABASE=Dept_MR;UID=guest;PWD=password')
The suggestion to remove the try...except block did not work for me. Now the actual import is throwing the error as below:
Traceback (most recent call last):
File "C:\Users\a\workspace\TestPyProject\src\helloworld.py", line 2, in <module>
import pyodbc
File "C:\Users\a\AppData\Local\Continuum\Anaconda3\Lib\site-packages\sqlalchemy\dialects\mssql\pyodbc.py", line 105, in <module>
from .base import MSExecutionContext, MSDialect, VARBINARY
I do have pyodbc installed and the import and connect works fine with the command line on windows.
thank you
The problem here is that the pyodbc module is not importing in your try / except block. I would highly recommend not putting import statements in try blocks. First, you would want to make sure you have pyodbc installed (pip install pyodbc), preferably in a virtualenv, then you can do something like this:
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=PXLstr,17;DATABASE=Dept_MR;UID=guest;PWD=password')
cursor = cnxn.cursor()
cursor.execute('SELECT 1')
for row in cursor.fetchall():
print(row)
If you're running on Windows (it appears so, given the DRIVER= parameter), take a look at virtualenvwrapper-win for managing Windows Python virtual environments: https://pypi.python.org/pypi/virtualenvwrapper-win
Good luck!
Flipper's answer helped to establish that the problem was with referencing an incorrect library in External Libraries list in eclipse. After fixing it, the issue was resolved.
What is the name of your python file? If you inadvertently name it as 'pyodbc.py', you got that error. Because it tries to import itself instead of the intended pyodbc module.
here is the solution!
simply install and use 'pypyodbc' instead of 'pyodbc'!
I have my tested example as below. change your data for SERVER_NAME and DATA_NAME and DRIVER. also put your own records.good luck!
import sys
import pypyodbc as odbc
records = [
['x', 'Movie', '2020-01-09', 2020],
['y', 'TV Show', None, 2019]
]
DRIVER = 'ODBC Driver 11 for SQL Server'
SERVER_NAME = '(LocalDB)\MSSQLLocalDB'
DATABASE_NAME = 'D:\ASPNET\SHOJA.IR\SHOJA.IR\APP_DATA\DATABASE3.MDF'
conn_string = f"""
Driver={{{DRIVER}}};
Server={SERVER_NAME};
Database={DATABASE_NAME};
Trust_Connection=yes;
"""
try:
conn = odbc.connect(conn_string)
except Exception as e:
print(e)
print('task is terminated')
sys.exit()
else:
cursor = conn.cursor()
insert_statement = """
INSERT INTO NetflixMovies
VALUES (?, ?, ?, ?)
"""
try:
for record in records:
print(record)
cursor.execute(insert_statement, record)
except Exception as e:
cursor.rollback()
print(e.value)
print('transaction rolled back')
else:
print('records inserted successfully')
cursor.commit()
cursor.close()
finally:
if conn.connected == 1:
print('connection closed')
conn.close()

can't execute '.read create.sql'

This might be an obvious error but I'm trying to create a database within python from a script I've already created.
conn = sqlite3.connect('testDB')
c = conn.cursor()
c.execute('.read create.sql')
This gives an error "sqlite3.OperationalError: near ".": syntax error"
If I do the same thing at the sqlite3 cmd line it works fine
[me#myPC ~]$ sqlite3 testDB
SQLite version 3.3.6
Enter ".help" for instructions
sqlite> .read create.sql
sqlite>
It seems that any commands that start with a . give me problems.
just pass the content of the file to the .execute method:
conn = sqlite3.connect('testDB')
c = conn.cursor()
SQL = open('create.sql').read()
c.executescript(SQL)
I would suppose that commands starting with . are for the CLI client itself, not for the backend.
So you have no chance to do so and would have to do file reading and executing the queries by yourself, i.e. in Python.

Categories

Resources