Unable to Open access database using Python - python-3.x

I am unable to open an access database using python. Below is the code and the error message. I even tried going to control panel checking where the path of the odbc file is pointing to. It shows up in the correct path. %windir%\syswow64\odbcad32.exe not sure how to avoid this message, The below code also shows the drivers that are available.
import pyodbc
def show_odbc_sources():
sl = []
source = odbc.SQLDataSources(odbc.SQL_FETCH_FIRST)
while source:
dsn, driver = source
sl.append('%s [%s]' % (dsn, driver))
source = odbc.SQLDataSources(odbc.SQL_FETCH_NEXT)
sl.sort()
print('\n'.join(sl))
if __name__ == '__main__':
show_odbc_sources()
conn = pyodbc.connect(r'driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\username\\Desktop\\E CX DB.accdb;')
cursor = conn.cursor()
Errors That i get:
Excel Files [Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)]
MS Access Database [Microsoft Access Driver (*.mdb, *.accdb)]
Sample Amazon Redshift DSN [Amazon Redshift (x64)]
---------------------------------------------------------------------------
InterfaceError Traceback (most recent call last)
<ipython-input-12-816aa9101ab7> in <module>()
16 show_odbc_sources()
17
---> 18 conn = pyodbc.connect(r'driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\username\\Desktop\\E CX DB.accdb;')
19 cursor = conn.cursor()
InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

That is the driver i have which is 32 bit version.
It appears that you are running a 64-bit version of Python, so pyodbc cannot see the 32-bit version of the Access ODBC driver. You'll either need to switch to a 32-bit version of Python or switch to the 64-bit version of the Access ODBC driver.

Related

Accessing Excel as a database using groovy.sql [duplicate]

This question already has answers here:
sun.jdbc.odbc.JdbcOdbcDriver not working with jdk 1.8
(2 answers)
java.sql.SQLException: No suitable driver found for jdbc:odbc:Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=D:\Users\
(4 answers)
Closed 1 year ago.
I am trying to access Excel as a database using the groovy.sql package, which is a GDK extension to JDBC. I am aware that Excel is not a database and that for most tasks Apache POI works better. I am using an Excel file named weather.xlsx as a test document. The workbook contains only one sheet which looks like this:
City
Temperature
Denver
19
Boston
12
New York
22
I am using this code:
import groovy.sql.Sql
class ExcelAsDB {
static void main(args) {
def sql = Sql.newInstance(
"""jdbc:odbc:Driver=
{Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};
DBQ=C:\\path_to_file\\weather.xlsx;READONLY=false""", '', '')
println "City\t\tTemperature"
sql.eachRow('SELECT * FROM [temperatures$]') {
println "${it.city}\t\t${it.temperature}"
}
}
}
When I run the code, I get the following error message:
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:odbc:Driver=
{Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};
DBQ=C:\path_to_file\weather.xlsx;READONLY=false
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at groovy.sql.Sql.newInstance(Sql.java:396)
at groovy.sql.Sql$newInstance.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:157)
at Excel.main(Excel.groovy:7)
I've read in similar questions such as java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why? and JDBC ODBC Driver Connection that the ODBC bridge was removed from Java with Java 8. However, I was under the impression that if I connect directly to the Excel driver, rather than setup a DSN for the Excel file, I should be able to access the file anyway.
I am using a Windows computer and have confirmed that the Excel Driver is installed. I am using Groovy Version: 3.0.8 JVM: 16 Vendor: Oracle Corporation OS: Windows 10.

cx_Oracle returning zero rows

I am new to connecting to oracle db (version 19.3) through python 3.6. I am not getting any rows in return. Please tell me what am I missing here?
I think all connection is set up correctly because it's not showing any connection error or invalid password error. Tried using fetchall(), fetchmany(), rowcount etc. everything is returning zero. I tried printing the cursor object itself, which is working. I ran the query in my DB. I have Oracle DB 19.3 installed locally, using Oracle SQL developer for running SQL. Anything else I need to install?
import cx_Oracle
conn = cx_Oracle.connect("username", "password", "localhost/orcl")
cur = conn.cursor()
cur.execute('select * from emp')
for line in cur:
print(line)
cur.close()
conn.close()
After running
delete from emp;
your python program will display zero rows, as you report.
You may wish to INSERT one or more rows before running it.
You may also find the interface offered by sqlalchemy to be more convenient.
It offers app portability across Oracle and other DB backends.
Cf https://developer.oracle.com/dsl/prez-python-queries.html

Error: Data source name not found and no default driver specified (0) (SQLDriverConnect)

I'm trying to set up a connection between Python 3.7 and Teradata SQL Assistant. Below is the code I'm using, but I'm getting the following error... "InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)'). Any idea why I'm getting this error?
import pyodbc
print ('Connecting to Teradata')
tdta_cnxn = pyodbc.connect(DSN='xxx',UID='xxx',PWD='xxx')
tdta_cursor = tdta_cnxn.cursor()
print ('Success!')
You can run into this szenario based on which ODBC drivers you have. Sometimes it can happen, that ODBC is not shure which drive to take.
So you have to point it to this by just adding "Driver=Teradata Database ODBC Driver 16.10" or "Driver={Teradata}" (or what your driver is) to the connection parameters.
As an alternative you can connect via native Python driver teradatasql (https://pypi.org/project/teradatasql/).

How to to load a Pandas Data frame to Redshfit Server using OBDC driver?

I am relatively new to Python programming. I have searched previously answered questions related to this thoroughly but couldn't find a good solution.
Problem: I am intending to use the ODBC driver installed in my system to connect to Red-shift database. All entities - (Servername, host, port, Username, and password) are configured in the DSN. I was successfully able to make a connection to the database and read the table using the following code:
import pyodbc
import pandas as pd
conn = pyodbc.connect('DSN=AWSDW')
Query = """select *
from <table_name>
limit 10"""
df2 = pd.read_sql(Query,conn)
But the problem is I can get to load this dataframe in Redshift. Below is the code that I am trying to run:
engine = sqlalchemy.create_engine('postgresql+pyodbc://AWSDW')
df2.to_sql('Abhi_Testing_Python_2'
,engine
,schema='sandbox'
,index=False
,if_exists = 'replace')
I know there is something that need to be done in Connection string for create engine. But just don't know what?
I am open to using some other method as long as I don't have to hard code my username and password in the code.
I found that you can't use postgresql dialect with pyodbc driver.
https://www.codepowered.com/manuals/SQLAlchemy-0.6.9-doc/html/core/engines.html
So, I ended up not using the Amazon Driver which I installed. Used psycopg2 instead.
connection_string = 'postgresql+psycopg2://'+username+':'+password+'#'+HOST+':'+str(PORT)+'/'+DATABASE
engine = create_engine(connection_string)
This works. Only drawback was I had to hard code the HOST name in my code.

Reading excel file (.csv) using ODBC driver in Qt

I have a csv file that I'd like to parse in Qt. I'd like to use the sql plugin, but I'm not sure how to get things set up. I currently am unable to open the .csvfile from my Qt app--I have to manually open it then start my app in hopes to query from it.
If the file I'm trying to read isn't manually opened before I begin my app, I get the following driver error:
[Microsoft][ODBC Excel Driver] External table is not in the expected format.
[Microsoft][ODBC Excel Driver] General Warning Unable to open registry key 'Temporary (volatile) Jet DSN for process 0x1ae0 Thread 0x1f2c DBC 0x4c52a4 Excel.' QODBC3: Unable to connect.
Here's my setup...
Qt Creator Build/Version:
I am working in Qt 5.3 which I did not build from source--I downloaded the installer.
I have configured a few debugging kits, but the one i'm using currently uses the MSVC 2012 openGL 32 bit compiler (which I've got set to default).
I have both Visual Studio 2012 AND 2010 on my machine, which is 64bit.
I didn't have to make the sql drivers, they came installed already (available drivers: () ("QSQLITE", "QMYSQL", "QMYSQL3", "QODBC", "QODBC3", "QPSQL", "QPSQL7"))
My .pro file hooks to the sql plugin:
QT += core gui network sql
And I've got the following includes:
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
This is my code that establishes an Excel database connection and attempts a query:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
QString pathString = QString("C:\\MY_FILES\\test_work\\Xena\\Xena2544-2G\\Reports\\asdf_SN1_RFC2544_7_port_verify.csv");
db.setDatabaseName("DRIVER={Microsoft Excel Driver (*.xls)};DBQ=" + pathString );
if (!db.open())
{
QSqlError er = db.lastError();
QMessageBox::information(0, "Error", er.text());
}
if(db.open())
{
QSqlQuery query("select * from [" + QString("asdf_SN1_RFC2544_7_port_verify") + "$B13]"); //NEVER GETS HERE UNLESS i ALREADY MANUALLY OPENED THE FILE BEFORE RUNNING CODE.
QString process1Result = query.value(0).toString();
ui->verifyUnit1Status_lb->setText(process1Result);
}
File Permissions
- Full control
- modify
- read& execute
- read
- write
I'd really like to get this feature going. I would assume the error is in the connection string, but at this point I've tried for a couple hours with no success.
Thank you in advance.

Resources