I try to access db connection with python code, however I got problem with python db connection. here is my code and I am working with python version 2.7.10.
import pymysql
class SqlManager:
def __init__(self):
self.conn = None
self.cursor = None
self.host = "127.0.0.1"
self.port = 3306
self.user = "user"
self.passwd = "pw"
self.db_name = "db"
def connect(self):
self.conn = pymysql.connect(
host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db_name)
self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
self.conn.autocommit(True)
return True
def description(self):
cur = self.cursor.execute("SELECT * FROM user")
for row in cur:
print(row)
Actually I guess I got Attribute error of Nonetype maybe the connection declare in init part with None, but I made connection in connect part, so I thought that it would work, but I was not.
Please suggest me what I need to fix or better way to use it.
Thanks for helping me.
In the constructor you do,
self.cursor = None
And then you do this in description
method without initializing the property,
cur = self.cursor.execute("SELECT * FROM user")
You might want to change it to,
self.conn.cursor.execute("SELECT * FROM user")
And of course you need to call the connect
method after initializing this class.