-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_connector.py
53 lines (45 loc) · 2 KB
/
db_connector.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import MySQLdb as mariadb
from .db_credentials import host, user, passwd, db
def connect_to_database(host = host, user = user, passwd = passwd, db = db):
'''
connects to a database and returns a database objects
'''
db_connection = mariadb.connect(host,user,passwd,db)
return db_connection
def execute_query(db_connection = None, query = None, query_params = ()):
'''
executes a given SQL query on the given db connection and returns a Cursor object
db_connection: a MySQLdb connection object created by connect_to_database()
query: string containing SQL query
returns: A Cursor object as specified at https://www.python.org/dev/peps/pep-0249/#cursor-objects.
You need to run .fetchall() or .fetchone() on that object to actually acccess the results.
'''
if db_connection is None:
print("No connection to the database found! Have you called connect_to_database() first?")
return None
if query is None or len(query.strip()) == 0:
print("query is empty! Please pass a SQL query in query")
return None
print("Executing %s with %s" % (query, query_params))
# Create a cursor to execute query. Why? Because apparently they optimize execution by retaining a reference according to PEP0249
cursor = db_connection.cursor()
'''
params = tuple()
#create a tuple of paramters to send with the query
for q in query_params:
params = params + (q)
'''
#TODO: Sanitize the query before executing it!!!
cursor.execute(query, query_params)
# this will actually commit any changes to the database. without this no
# changes will be committed!
db_connection.commit()
return cursor
if __name__ == '__main__':
print("Executing a sample query on the database using the credentials from db_credentials.py")
db = connect_to_database()
query = "SELECT * from Gods;"
results = execute_query(db, query)
print("Printing results of %s" % query)
for r in results.fetchall():
print(r)