I am making a Python project where I have to seek and retreive data from a database.
I tried making a class, in which I declare the connection and do my queries, here is moreless what I have so far.
import MySQLdb
dbc =("localhost","root","1234","users")
class sql:
db = MySQLdb.connect(dbc[0],dbc[1],dbc[2],dbc[3])
cursor = db.cursor()
def query(self,sql):
sql.cursor.execute(sql)
return sql.cursor.fetchone()
def rows(self):
return sql.cursor.rowcount
sqlI = sql()
print(sqlI.query("SELECT `current_points` FROM `users` WHERE `nick` = 'username';"))
So, the main problem is that the variable db
and cursor
are not callable from other def's/functions from the same Class. What I'd like to get, is a polished query, where I can make queries and retreive it's content. This would summarize my code, therefore I should do.
You can use constructor for the connection. When the object of class will created the constructor will invoke automatically.
I usually use psycopg2 / postgres, but this is the basic DB class that I often use, with Python's SQLite as an example:
This will let you use the
Database
class either normally likedb = Database('db_file.sqlite)
or in awith
statement:and the connection will automatically commit and close when the
with
statement exits.Then, you can encapsulate specific queries that you do often in methods and make them easy to access. For example, if you're dealing with transaction records, you could have a method to get them by date:
Here's some sample code where we create a table, add some data, and then read it back out:
I hope this helps!
That's not how you write classes in Python. You need to define your connection and cursor inside the
__init__
method, and refer to them viaself
.