Connecting to SQLite3 server using PyODBC, Python
I am trying to test a class that loads data from SQL server given a query. For this I was asked to use sqlite3
. Now the problem is that while the class manages to easily connect to the real database, I am struggling to connect to the temporary server sqlite3
I am creating since I cannot figure out what the connection string should look like. I am using pyodbc
in a class to connect to databases. So, does anyone have an idea on how the connection string should look like?
The class looks like this:
import petl as etl
import pyodbc
class Loader:
"""
This is a class from which one can load data from an SQL server.
"""
def __init__(self, connection_string):
"""
This is the initialization file, and it requires the connection_string.
:param connection_string:
:type connection_string: str
:return:
"""
self.connection = pyodbc.connect(connection_string)
def loadFromSQL(self, query):
"""
This function loads the data according to the query passed in query.
:param query:
:type query: str
"""
self.originalTableETL = etl.fromdb(self.connection, query)
self.originalTablePD = etl.todataframe(self.originalTableETL)
And the temporary server sqlite3
looks like this
import sqlite3 as lite
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS test_table")
cur.execute("CREATE TABLE test_table(col1 TEXT, col2 TEXT)")
cur.execute("INSERT INTO test_table VALUES('Hello', 'world!')")
So, I want to enter something like
tester = Loader('connection_string_goes_here')
tester.loadFromSQL("SELECT * FROM test_table")
EDIT
Ok, I searched the web a bit and found that a possible connection string
"DRIVER={SQL Server};SERVER=localhost;DATABASE=test.db;Trusted_connection=yes"
. However, the connection times out after a while and returns the following error message:
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect)')
Which I found strange because it is local and because I didn’t provide a password. I have also tried specifying the exact pathname to no avail.
Best,
Victor
source to share
I solved the problem! Downloaded the ODCB driver for sqlite3
from http://www.ch-werner.de/sqliteodbc/ and defined a connection string such as
"DRIVER={SQLite3 ODBC Driver};SERVER=localhost;DATABASE=test.db;Trusted_connection=yes"
And it worked, hope it helps people!
source to share