PyMySQL==0.9.2 python 3.6.4 I simplified my code a little, it is supposed to run on many sql databases. My current struggle is with pymysql and mysql. main: $>cat testje.py
#!/usr/bin/env python
import pymysql as dbdr
from dbconnections import mysql as dbc
with dbc.connect(dbdr) as conn:
print(conn)
$>cat dbconnections/mysql.py
def connect(db):
dbc = db.connect(host='127.0.0.1', user='cistats', password='bloemkool',
db='mysql', port=int(3306)
# cursorclass=pymysql.cursors.DictCursor
)
print(dbc)
return dbc
output: $>./testje.py
<pymysql.connections.Connection object at 0x10a72e5c0>
<pymysql.cursors.Cursor object at 0x10b16cfd0>
It shows that in the connect function dbc is a Connection object. Why is it magically appearing as Cursor object in main? How can I fix this? In main I really am expecting a Connection object.
The same structure is working ok for cx_Oracle, psycopg2 and pytds drivers.
As Ignacio Vazquez-Abrams mentioned, the cause is that when using with
the connect().enter() is called. This is the same for other drivers but the other drivers just have:
def __enter__(self):
return self
and pymysql has:
def __enter__(self):
"""Context manager that returns a Cursor"""
return self.cursor()
So I changed my code to simply: conn = dbc.connect(...)
and now it works for all driver I have used so far.