-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
91 lines (66 loc) · 2.17 KB
/
database.py
File metadata and controls
91 lines (66 loc) · 2.17 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import MySQLdb
class DataBase():
""" Class to interact with relational database """
def __init__(self, host, user, dbPass, name, port = 3306):
"""
Init method to create a new connection to MySQL Database.
"""
connection = MySQLdb.connect(host=host, user=user, passwd=dbPass, db=name, charset="utf8", init_command="set names utf8", port=port)
self.cursor = connection.cursor(MySQLdb.cursors.DictCursor)
""" SELECT functions. """
def get_all(self, cursor, table):
"""
Fetch all rows from any table.
:type cursor: cursor
:param cursor: Pointer to DB Connection.
:type table: string
:param table: SQL Table name.
:rtype: list
:return: data.
"""
tempList = []
query = 'SELECT * FROM ' + table + ' ORDER BY id DESC;'
cursor.execute(query)
for domain in cursor.fetchall():
tempList.append(domain)
return tempList
def get(self, cursor, table, field, value):
"""
Fetch information from any table by any field.
:type cursor: cursor
:param cursor: Pointer to DB Connection.
:type table: string
:param table: SQL Table Name.
:type field: string
:param field: SQL Field Table Name.
:type value: string
:param value: Value to search.
:rtype: dict
:return: Model Information.
"""
query = 'SELECT * FROM ' + table + ' WHERE ' + field + ' = "' + str(value) + '";'
cursor.execute(query)
return cursor.fetchone()
""" UPDATE functions. """
def update_by_id(self, cursor, table, changes, where_id):
"""
Update fields in any table.
:type cursor: cursor
:param cursor: Pointer to DB Connection.
:type table: string
:param table: SQL Table Name.
:type changes: dict
:param changes: Dictionary that contains field to update and their related value..
:type where_id: string
:param where_id: ID row value where the update will be performed.
"""
change = ', '.join("{!s} = {!r}".format(k,str(v)) for (k,v) in changes.iteritems())
query = 'UPDATE ' + table + ' SET ' + change + ' WHERE id = ' + str(where_id) + ';'
try:
cursor.execute(query)
except Exception, e:
print e