Repository navigation
Expand file tree
/
Copy pathmySQL.py
More file actions
342 lines (262 loc) · 9.75 KB
/
Copy pathmySQL.py
File metadata and controls
342 lines (262 loc) · 9.75 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# by jensdiemer.de (steht unter GPL-License)
"""
MySQLdb wrapper
Allgemeine Routinen für eine einfachere SQL Benutzung
Benötigt MySQLdb download unter:
http://sourceforge.net/projects/mysql-python/
Information
-----------
Generell wird keine Tracebacks abgefangen, das muß immer im eigentlichen
Programm erledigt werden!
Wie man die Klasse benutzt, kann man unten sehen ;)
ToDo
----
* Es wird immer das paramstyle 'format' benutzt. Also mit %s escaped
"""
__version__="0.0.9"
__history__="""
v0.0.9
- in update() wird nun auch die where-value SQL-Escaped
v0.0.8
- bei select() werden nun auch die select-values mit der SQLdb escaped
- methode _make_values() gelöscht und einfach durch tuple() erstetzt ;)
v0.0.7
- Statt query_fetch_row() wird der Cursor jetzt mit MySQLdb.cursors.DictCursor erstellt.
Somit liefern alle Abfragen ein dict zurück! Das ganze funktioniert auch mit der uralten
MySQLdb v0.9.1
- DEL: query_fetch_row()
- NEU: fetchall()
v0.0.6
- NEU: query_fetch_row() und exist_table_name()
v0.0.5
- Stellt über self.conn das Connection-Objekt zur verfügung
v0.0.4
- Bugfixes
- Debugfunktion eingefügt
- Beispiel hinzugefügt
- SQL "*"-select verbessert.
v0.0.3
- Allgemeine SQL insert und update Funktion eingefügt
- SQL-where-Parameter kann nun auch meherere Bedingungen haben
v0.0.2
- Allgemeine select-SQL-Anweisung
- Fehlerausgabe bei fehlerhaften SQL-Anfrage
v0.0.1
- erste Release
"""
try:
import MySQLdb
except ImportError, e:
print "Content-type: text/html\n"
print "<h1>Error</h1>"
print "<h3>MySQLdb import error! Modul 'python-mysqldb' not installed???</h3>"
print "<p>Error Msg.:<br/>%s</p>" % e
print '<a href="http://sourceforge.net/projects/mysql-python/">MySQLdb project page</a>'
import sys
sys.exit(0)
class mySQL:
"""
Klasse, die nur allgemeine SQL-Funktionen beinhaltet
"""
def __init__( self, *args, **kwargs ):
self.conn = MySQLdb.connect( *args, **kwargs )
self.cursor = self.conn.cursor( MySQLdb.cursors.DictCursor )
self.tableprefix = ""
# Bei debug=True werden die SQL-Befehle aufgegeben
self.debug = False
def get( self, SQLcommand, SQL_values = () ):
"""kombiniert execute und fetchall mit Tabellennamenplatzhalter"""
self.cursor.execute(
SQLcommand.replace("$tableprefix$", self.tableprefix),
SQL_values
)
return self.cursor.fetchall()
def fetchall( self, SQLcommand, SQL_values = () ):
""" kombiniert execute und fetchall """
self.cursor.execute( SQLcommand, SQL_values )
return self.cursor.fetchall()
def get_tables( self ):
"""
Liefert alle Tabellennamen die das self.tableprefix haben
"""
tables = []
for table in self.fetchall( "SHOW TABLES" ):
tablename = table.values()[0]
if tablename.startswith( self.tableprefix ):
tables.append( tablename )
return tables
def insert( self, table, data ):
"""
Vereinfachter Insert, per dict
data ist ein Dict, wobei die SQL-Felder den Key-Namen im Dict entsprechen muß!
"""
items = data.keys()
values = tuple( data.values() )
SQLcommand = "INSERT INTO %(prefix)s%(table)s ( %(items)s ) VALUES ( %(values)s );" % {
"prefix" : self.tableprefix,
"table" : table,
"items" : ",".join( items ),
"values" : ",".join( ["%s"]*len(values) ) # Platzhalter für SQLdb-escape
}
if self.debug:
print "-"*80
print "db.insert - Debug:"
print "SQLcommand.:",SQLcommand
print "values.....:",values
print "-"*80
self.cursor.execute( SQLcommand, values )
def update( self, table, data, where, limit=False ):
"""
Vereinfachte SQL-update Funktion
"""
data_keys = data.keys()
values = data.values()
values.append( where[1] )
values = tuple( values )
if limit:
limit = "LIMIT %s" % limit
else:
limit = ""
SQLcommand = "UPDATE %(prefix)s%(table)s SET %(set)s WHERE %(where)s %(limit)s;" % {
"prefix" : self.tableprefix,
"table" : table,
"set" : ",".join( [str(i)+"=%s" for i in data_keys] ),
"where" : where[0] + "=%s",
"limit" : limit
}
if self.debug:
print "-"*80
print "db.update - Debug:"
print "SQLcommand.:",SQLcommand
print "values.....:",values
print "-"*80
self.cursor.execute( SQLcommand, values )
def select( self, select_items, from_table, where=None, order=None, limit=None, maxrows=0, how=1 ):
"""
Allgemeine SQL-SELECT Anweisung
where, order und limit sind optional
where
-----
Die where Klausel ist ein wenig special.
einfache where Klausel:
where=("parent",0) ===> WHERE `parent`="0"
mehrfache where Klausel:
where=[("parent",0),("id",0)] ===> WHERE `parent`="0" and `id`="0"
maxrows - Anzahl der zurückgegebenen Datensätze, =0 alle Datensätze
how - Form der zurückgegebenen Daten. =1 -> als Dict, =0 als Tuple
"""
SQLcommand = "SELECT " + ",".join( select_items )
SQLcommand += " FROM %s%s" % ( self.tableprefix, from_table )
SQL_parameters_values = []
if where != None:
if type( where[0] ) == str:
# es ist nur eine where-Regel vorhanden.
# Damit die folgenden Anweisungen auch gehen
where = [ where ]
where_string = []
for item in where:
where_string.append( item[0] + "=%s" )
SQL_parameters_values.append( item[1] )
SQLcommand += ' WHERE %s' % " and ".join( where_string )
if order != None:
SQLcommand += " ORDER BY %s %s" % order
if limit != None:
SQLcommand += " LIMIT %s,%s" % limit
if self.debug:
print "-"*80
print "db.select - Debug:"
print "SQLcommand:", SQLcommand
self.cursor.execute( SQLcommand, tuple( SQL_parameters_values ) )
return self.cursor.fetchall()
def exist_table_name( self, table_name ):
""" Überprüft die existens eines Tabellen-Namens """
self.cursor.execute( "SHOW TABLES" )
for line in self.cursor.fetchall():
if line[0] == table_name:
return True
return False
def dump_select_result( self, result ):
print "*** dumb select result ***"
for i in xrange( len(result) ):
print "%s - %s" % (i, result[i])
def close( self ):
"Connection schließen"
self.conn.close()
if __name__ == "__main__":
db = mySQL(
host = "localhost",
user = "SQL-DB-Username",
passwd = "SQL-DB-Password",
db = "SQL-DB-Name"
)
#~ #----[PyLucid]----------------------------
#~ import sys
#~ sys.path.insert( 0, "../" )
#~ from config import dbconf
#~ db = mySQL(
#~ host = dbconf["dbHost"],
#~ user = dbconf["dbUserName"],
#~ passwd = dbconf["dbPassword"],
#~ db = dbconf["dbDatabaseName"],
#~ )
#~ #-----------------------------------------
# Prefix for all SQL-commands:
db.tableprefix = "test_"
# Prints all SQL-command:
db.debug = True
SQLcommand = "CREATE TABLE %sTestTable (" % db.tableprefix
SQLcommand += "id INT( 11 ) NOT NULL AUTO_INCREMENT,"
SQLcommand += "data1 VARCHAR( 50 ) NOT NULL,"
SQLcommand += "data2 VARCHAR( 50 ) NOT NULL,"
SQLcommand += "PRIMARY KEY ( id )"
SQLcommand += ") COMMENT = '%s - temporary test table';" % __file__
print "\n\nCreat a temporary test table - execute SQL-command directly."
try:
db.cursor.execute( SQLcommand )
except Exception, e:
print "Can't create table: '%s'" % e
print "\n\nSQL-insert Function:"
db.insert(
table = "TestTable",
data = { "data1" : "Value A 1", "data2" : "Value A 2" }
)
print "\n\nadds a new value:"
db.insert(
table = "TestTable",
data = { "data1" : "Value B 1", "data2" : "Value B 2" }
)
print "\n\nSQL-select Function (db.select):"
result = db.select(
select_items = ["id","data1","data2"],
from_table = "TestTable",
#~ where = ("parent",0)#,debug=1
)
db.dump_select_result( result )
print "\n\nUpdate an item (db.update)."
data = { "data1" : "NewValue1!"}
db.update(
table = "TestTable",
data = data,
where = ("id",1),
limit = 1
)
print "\n\nSee the new value (db.select):"
result = db.select(
select_items = ["data1"],
from_table = "TestTable",
where = ("id",1)
)
db.dump_select_result( result )
print "\n\nSee all values via SQL '*'-select:"
result = db.select(
select_items = "*",
from_table = "TestTable",
#~ where = ("id",1)
)
db.dump_select_result( result )
print "\n\nDelete the temporary test Table."
db.cursor.execute( "DROP TABLE %sTestTable" % db.tableprefix )
print "\n\nClose SQL-connection."
db.close()