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()
Related
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 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.
I'm trying to execute this simple python script but it seems to do nothing: I don't get any error, I try to execute the query directly on sqlite3 and it works....I don't have any idea why isn't working, can anyone help me?
import sqlite3 as lite
import sys
con = None
try:
con = lite.connect('/home/pi/Moranberries/web/moranberries.db')
cur = con.cursor()
cur.execute("INSERT INTO sensor_interior (temperatura,humedad) VALUES (111,222)")
except lite.Error, e:
print "Error %s:" % e.args[0]
sys.exit(1)
finally:
if con:
con.close()
To execute this script I named it prueba.py an call it from terminal as this:
python prueba.py
There is no error message.
You're not committing your changes to the DB. If you call con.commit() after cur.execute, it should write the changes.
I have a raspberry pi that records temperature and stores them in a MySQL database on my website. I often toy with the script, so I am hitting ctrl+c on the running script and re executing it. I would like to properly issue close() on the database connection. How can I run a line of code when the script is exited in python?
import MySQLdb
con = MySQLdb.connect(...)
cursor = con.cursor()
# ...
#if script closes:
#con.close()
import MySQLdb
con = MySQLdb.connect(...)
cursor = con.cursor()
try:
# do stuff with your DB
finally:
con.close()
The finally clause is executed on success as well as on error (exception).
If you hit Ctrl-C, you get a KeyboardInterrupt exception.
or:
import atexit
def close_db(con):
con.close()
# any other stuff you need to run on exiting
import MySQLdb
con = MySQLdb.connect(...)
# ...
atexit.register(close_db, con=con)
See here for more info.
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 ...