时间:2021-07-01 10:21:17 帮助过:2人阅读
1 import sqlite3 2 from os import makedirs, removedirs, unlink 3 from os.path import dirname, exists 4 5 DB_FILE = ‘sqlite_test/test.db‘ 6 DB_DIR = dirname(DB_FILE) 7 8 if not exists(DB_FILE): 9 if not exists(DB_DIR): 10 makedirs(DB_DIR) 11 dbfile = file(DB_FILE, ‘wb‘) 12 dbfile.close() 13 14 cxn = sqlite3.connect(DB_FILE) 15 cur = cxn.cursor() 16 cur.execute(‘CREATE TABLE users(login VARCHAR(8), uid INTEGER)‘) 17 cur.execute(‘INSERT INTO users VALUES("john", 100)‘) 18 cur.execute(‘INSERT INTO users VALUES("jane", 101)‘) 19 20 cur.execute(‘SELECT login, uid FROM users‘) 21 for eachUser in cur.fetchall(): 22 print eachUser 23 24 cur.execute(‘DROP TABLE users‘) 25 cur.close() 26 cxn.commit() 27 cxn.close() 28 unlink(DB_FILE) 29 removedirs(DB_DIR)sqlite3test.py
1 #!/usr/bin/env python 2 3 import os 4 from random import randrange as rrange 5 6 COLSIZ = 10 7 RDBMSs = {‘s‘: ‘sqlite‘, ‘m‘: ‘mysql‘, ‘g‘:‘gadfly‘} 8 DB_EXC = None 9 10 def setup(): 11 return RDBMSs[raw_input(‘‘‘ 12 Choose a database system: 13 14 (M)ySQL 15 (G)adfly 16 (S)qlite 17 18 Enter choice:‘‘‘).strip().lower()[0]] 19 20 def connect(db, dbName): 21 global DB_EXC 22 dbDir = ‘%s_%s‘ % (db, dbName) 23 24 if db == ‘sqlite‘: 25 try: 26 import sqlite3 27 except ImportError, e: 28 try: 29 from pysqlite2 import dbapi2 as sqlite3 30 except ImportError, e: 31 return None 32 33 DB_EXC = sqlite3 34 if not os.path.isdir(dbDir): 35 os.mkdir(dbDir) 36 cxn = sqlite3.connect(os.path.join(dbDir, dbName)) 37 38 elif db == ‘mysql‘: 39 try: 40 import MySQLdb 41 import _mysql_exceptions as DB_EXC 42 except ImportError, e: 43 return None 44 45 try: 46 cxn = MySQLDb.connect(db=dbName) 47 except _mysql_exceptions.OperationalError, e: 48 cxn = MySQLdb.connect(user=‘root‘) 49 try: 50 cxn.query(‘DROP DATABASE %s‘ % dbName) 51 except DB_EXC.OperationalError, e: 52 pass 53 cxn.query(‘CREATE DATABASE %s‘ % dbName) 54 cxn.query("GRANT ALL ON %s.* to ‘‘@‘localhost‘" % dbName) 55 cxn.commit() 56 cxn.close() 57 cxn = MySQLdb.connect(db=dbName) 58 59 elif db == ‘gadfly‘: 60 try: 61 from gadfly import gadfly 62 DB_EXC = gadfly 63 except ImportError, e: 64 return None 65 66 try: 67 cxn = gadfly(dbName, dbDir) 68 except IOError, e: 69 cxn = gadfly() 70 if not os.path.isdir(dbDir): 71 os.mkdir(dbDir) 72 cxn.startup(dbName, dbDir) 73 else: 74 return None 75 return cxn 76 77 def create(cur): 78 try: 79 cur.execute(‘‘‘ 80 CREATE TABLE users ( 81 login VARCHAR(8), 82 uid INTEGER, 83 prid INTEGER) 84 ‘‘‘) 85 except DB_EXC.OperationalError, e: 86 drop(cur) 87 create(cur) 88 89 drop = lambda cur: cur.execute(‘DROP TABLE users‘) 90 91 NAMES = ( 92 (‘aaron‘, 8312), (‘angela‘, 7603), (‘dave‘, 7306), 93 (‘davina‘,7902), (‘elliot‘, 7911), (‘ernie‘, 7410), 94 (‘jess‘, 7912), (‘jim‘, 7512), (‘larry‘, 7311), 95 (‘leslie‘, 7808), (‘melissa‘, 8602), (‘pat‘, 7711), 96 (‘serena‘, 7003), (‘stan‘, 7607), (‘faye‘, 6812), 97 (‘amy‘, 7209), 98 ) 99 100 def randName(): 101 pick = list(NAMES) 102 while len(pick) > 0: 103 yield pick.pop(rrange(len(pick))) 104 105 def insert(cur, db): 106 if db == ‘sqlite‘: 107 cur.executemany("INSERT INTO users VALUES(?, ?, ?)", 108 [(who, uid, rrange(1, 5)) for who, uid in randName()]) 109 elif db == ‘gadfly‘: 110 for who, uid in randName: 111 cur.execute("INSERT INTO users VALUES(?, ?, ?)", 112 (who, uid, rrange(1,5))) 113 elif db == ‘mysql‘: 114 cur.executemay("INSERT INTO users VALUES(%s, %s, %s)", 115 [(who, uid, rrange(1,5)) for who, uid, in randName()]) 116 117 getRC = lambda cur: cur.rowcount if hasattr(cur, ‘rowcount‘) else -1 118 119 def update(cur): 120 fr = rrange(1,5) 121 to = rrange(1,5) 122 cur.execute( 123 "UPDATE users SET prid=%d WHERE prid=%d" % (to, fr)) 124 return fr, to, getRC(cur) 125 126 def delete(cur): 127 rm = rrange(1,5) 128 cur.execute(‘DELETE FROM users WHERE prid=%d‘ % rm) 129 return rm, getRC(cur) 130 131 def dbDump(cur): 132 cur.execute(‘SELECT login, uid, prid FROM users‘) 133 print ‘\n%s%s%s‘ % (‘LOGIN‘.ljust(COLSIZ), 134 ‘USERID‘.ljust(COLSIZ), ‘PROJ#‘.ljust(COLSIZ)) 135 for data in cur.fetchall(): 136 print ‘%s%s%s‘ % tuple([str(s).title().ljust(COLSIZ)137 for s in data]) 138 def main(): 139 db = setup() 140 print ‘*** Connecting to %r database‘ % db 141 cxn = connect(db, ‘test‘) 142 143 if not cxn: 144 print ‘ERROR: %r not supported, exiting‘ % db 145 return 146 cur = cxn.cursor() 147 148 print ‘\n*** Creating users table‘ 149 create(cur) 150 151 print ‘\n*** Inserting names into table‘ 152 insert(cur, db) 153 dbDump(cur) 154 155 print ‘\n*** Randomly moving folks‘, 156 fr, to, num = update(cur) 157 print ‘from on group (%d) to another (%d)‘ % (fr, to) 158 print ‘\t(%d users moved)‘ % num 159 dbDump(cur) 160 161 print ‘\n*** Randomly choosing group.‘, 162 rm, num = delete(cur) 163 print ‘(%d) to delete‘ % rm 164 print ‘\t(%d users removed)‘ % num 165 dbDump(cur) 166 167 print ‘\n*** Drop users table‘ 168 drop(cur) 169 cur.close() 170 cxn.commit() 171 cxn.close() 172 173 if __name__ == ‘__main__‘: 174 main()shuffle_db.py 21.3 对象-关系管理器(ORMs) 考虑对象,而不是SQL
21 数据库编程 - 《Python 核心编程》
标签: