转自:http://www.cnblogs.com/hongten
1 import sqlite3 2 import os 3 '''SQLite数据库是一款非常小巧的嵌入式开源数据库软件,也就是说 4 没有独立的维护进程,所有的维护都来自于程序本身。 5 在python中,使用sqlite3创建数据库的连接,当我们指定的数据库文件不存在的时候 6 连接对象会自动创建数据库文件;如果数据库文件已经存在,则连接对象不会再创建 7 数据库文件,而是直接打开该数据库文件。 8 连接对象可以是硬盘上面的数据库文件,也可以是建立在内存中的,在内存中的数据库 9 执行完任何操作后,都不需要提交事务的(commit) 10 11 创建在硬盘上面: conn = sqlite3.connect('c:\\test\\test.db') 12 创建在内存上面: conn = sqlite3.connect('"memory:') 13 14 下面我们一硬盘上面创建数据库文件为例来具体说明: 15 conn = sqlite3.connect('c:\\test\\hongten.db') 16 其中conn对象是数据库链接对象,而对于数据库链接对象来说,具有以下操作: 17 18 commit() --事务提交 19 rollback() --事务回滚 20 close() --关闭一个数据库链接 21 cursor() --创建一个游标 22 23 cu = conn.cursor() 24 这样我们就创建了一个游标对象:cu 25 在sqlite3中,所有sql语句的执行都要在游标对象的参与下完成 26 对于游标对象cu,具有以下具体操作: 27 28 execute() --执行一条sql语句 29 executemany() --执行多条sql语句 30 close() --游标关闭 31 fetchone() --从结果中取出一条记录 32 fetchmany() --从结果中取出多条记录 33 fetchall() --从结果中取出所有记录 34 scroll() --游标滚动 35 36 ''' 37 38 #global var 39 #数据库文件绝句路径 40 DB_FILE_PATH = '' 41 #表名称 42 TABLE_NAME = '' 43 #是否打印sql 44 SHOW_SQL = True 45 46 def get_conn(path): 47 '''获取到数据库的连接对象,参数为数据库文件的绝对路径 48 如果传递的参数是存在,并且是文件,那么就返回硬盘上面改 49 路径下的数据库文件的连接对象;否则,返回内存中的数据接 50 连接对象''' 51 conn = sqlite3.connect(path) 52 if os.path.exists(path) and os.path.isfile(path): 53 print('硬盘上面:[{}]'.format(path)) 54 return conn 55 else: 56 conn = None 57 print('内存上面:[:memory:]') 58 return sqlite3.connect(':memory:') 59 60 def get_cursor(conn): 61 '''该方法是获取数据库的游标对象,参数为数据库的连接对象 62 如果数据库的连接对象不为None,则返回数据库连接对象所创 63 建的游标对象;否则返回一个游标对象,该对象是内存中数据 64 库连接对象所创建的游标对象''' 65 if conn is not None: 66 return conn.cursor() 67 else: 68 return get_conn('').cursor() 69 70 ############################################################### 71 #### 创建|删除表操作 START 72 ############################################################### 73 def drop_table(conn, table): 74 '''如果表存在,则删除表,如果表中存在数据的时候,使用该 75 方法的时候要慎用!''' 76 if table is not None and table != '': 77 sql = 'DROP TABLE IF EXISTS ' + table 78 if SHOW_SQL: 79 print('执行sql:[{}]'.format(sql)) 80 cu = get_cursor(conn) 81 cu.execute(sql) 82 conn.commit() 83 print('删除数据库表[{}]成功!'.format(table)) 84 close_all(conn, cu) 85 else: 86 print('the [{}] is empty or equal None!'.format(sql)) 87 88 def create_table(conn, sql): 89 '''创建数据库表:student''' 90 if sql is not None and sql != '': 91 cu = get_cursor(conn) 92 if SHOW_SQL: 93 print('执行sql:[{}]'.format(sql)) 94 cu.execute(sql) 95 conn.commit() 96 print('创建数据库表[student]成功!') 97 close_all(conn, cu) 98 else: 99 print('the [{}] is empty or equal None!'.format(sql)) 100 101 ############################################################### 102 #### 创建|删除表操作 END 103 ############################################################### 104 105 def close_all(conn, cu): 106 '''关闭数据库游标对象和数据库连接对象''' 107 try: 108 if cu is not None: 109 cu.close() 110 finally: 111 if conn is not None: 112 conn.close() 113 114 ############################################################### 115 #### 数据库操作CRUD START 116 ############################################################### 117 118 def save(conn, sql, data): 119 '''插入数据''' 120 if sql is not None and sql != '': 121 if data is not None: 122 cu = get_cursor(conn) 123 for d in data: 124 if SHOW_SQL: 125 print('执行sql:[{}],参数:[{}]'.format(sql, d)) 126 cu.execute(sql, d) 127 conn.commit() 128 close_all(conn, cu) 129 else: 130 print('the [{}] is empty or equal None!'.format(sql)) 131 132 def fetchall(conn, sql): 133 '''查询所有数据''' 134 if sql is not None and sql != '': 135 cu = get_cursor(conn) 136 if SHOW_SQL: 137 print('执行sql:[{}]'.format(sql)) 138 cu.execute(sql) 139 r = cu.fetchall() 140 if len(r) > 0: 141 for e in range(len(r)): 142 print(r[e]) 143 else: 144 print('the [{}] is empty or equal None!'.format(sql)) 145 146 def fetchone(conn, sql, data): 147 '''查询一条数据''' 148 if sql is not None and sql != '': 149 if data is not None: 150 #Do this instead 151 d = (data,) 152 cu = get_cursor(conn) 153 if SHOW_SQL: 154 print('执行sql:[{}],参数:[{}]'.format(sql, data)) 155 cu.execute(sql, d) 156 r = cu.fetchall() 157 if len(r) > 0: 158 for e in range(len(r)): 159 print(r[e]) 160 else: 161 print('the [{}] equal None!'.format(data)) 162 else: 163 print('the [{}] is empty or equal None!'.format(sql)) 164 165 def update(conn, sql, data): 166 '''更新数据''' 167 if sql is not None and sql != '': 168 if data is not None: 169 cu = get_cursor(conn) 170 for d in data: 171 if SHOW_SQL: 172 print('执行sql:[{}],参数:[{}]'.format(sql, d)) 173 cu.execute(sql, d) 174 conn.commit() 175 close_all(conn, cu) 176 else: 177 print('the [{}] is empty or equal None!'.format(sql)) 178 179 def delete(conn, sql, data): 180 '''删除数据''' 181 if sql is not None and sql != '': 182 if data is not None: 183 cu = get_cursor(conn) 184 for d in data: 185 if SHOW_SQL: 186 print('执行sql:[{}],参数:[{}]'.format(sql, d)) 187 cu.execute(sql, d) 188 conn.commit() 189 close_all(conn, cu) 190 else: 191 print('the [{}] is empty or equal None!'.format(sql)) 192 ############################################################### 193 #### 数据库操作CRUD END 194 ############################################################### 195 196 197 ############################################################### 198 #### 测试操作 START 199 ############################################################### 200 def drop_table_test(): 201 '''删除数据库表测试''' 202 print('删除数据库表测试...') 203 conn = get_conn(DB_FILE_PATH) 204 drop_table(conn, TABLE_NAME) 205 206 def create_table_test(): 207 '''创建数据库表测试''' 208 print('创建数据库表测试...') 209 create_table_sql = '''CREATE TABLE `student` ( 210 `id` int(11) NOT NULL, 211 `name` varchar(20) NOT NULL, 212 `gender` varchar(4) DEFAULT NULL, 213 `age` int(11) DEFAULT NULL, 214 `address` varchar(200) DEFAULT NULL, 215 `phone` varchar(20) DEFAULT NULL, 216 PRIMARY KEY (`id`) 217 )''' 218 conn = get_conn(DB_FILE_PATH) 219 create_table(conn, create_table_sql) 220 221 def save_test(): 222 '''保存数据测试...''' 223 print('保存数据测试...') 224 save_sql = '''INSERT INTO student values (?, ?, ?, ?, ?, ?)''' 225 data = [(1, 'Hongten', '男', 20, '广东省广州市', '13423****62'), 226 (2, 'Tom', '男', 22, '美国旧金山', '15423****63'), 227 (3, 'Jake', '女', 18, '广东省广州市', '18823****87'), 228 (4, 'Cate', '女', 21, '广东省广州市', '14323****32')] 229 conn = get_conn(DB_FILE_PATH) 230 save(conn, save_sql, data) 231 232 def fetchall_test(): 233 '''查询所有数据...''' 234 print('查询所有数据...') 235 fetchall_sql = '''SELECT * FROM student''' 236 conn = get_conn(DB_FILE_PATH) 237 fetchall(conn, fetchall_sql) 238 239 def fetchone_test(): 240 '''查询一条数据...''' 241 print('查询一条数据...') 242 fetchone_sql = 'SELECT * FROM student WHERE ID = ? ' 243 data = 1 244 conn = get_conn(DB_FILE_PATH) 245 fetchone(conn, fetchone_sql, data) 246 247 def update_test(): 248 '''更新数据...''' 249 print('更新数据...') 250 update_sql = 'UPDATE student SET name = ? WHERE ID = ? ' 251 data = [('HongtenAA', 1), 252 ('HongtenBB', 2), 253 ('HongtenCC', 3), 254 ('HongtenDD', 4)] 255 conn = get_conn(DB_FILE_PATH) 256 update(conn, update_sql, data) 257 258 def delete_test(): 259 '''删除数据...''' 260 print('删除数据...') 261 delete_sql = 'DELETE FROM student WHERE NAME = ? AND ID = ? ' 262 data = [('HongtenAA', 1), 263 ('HongtenCC', 3)] 264 conn = get_conn(DB_FILE_PATH) 265 delete(conn, delete_sql, data) 266 267 ############################################################### 268 #### 测试操作 END 269 ############################################################### 270 271 def init(): 272 '''初始化方法''' 273 #数据库文件绝句路径 274 global DB_FILE_PATH 275 DB_FILE_PATH = 'c:\\test\\hongten.db' 276 #数据库表名称 277 global TABLE_NAME 278 TABLE_NAME = 'student' 279 #是否打印sql 280 global SHOW_SQL 281 SHOW_SQL = True 282 print('show_sql : {}'.format(SHOW_SQL)) 283 #如果存在数据库表,则删除表 284 drop_table_test() 285 #创建数据库表student 286 create_table_test() 287 #向数据库表中插入数据 288 save_test() 289 290 291 def main(): 292 init() 293 fetchall_test() 294 print('#' * 50) 295 fetchone_test() 296 print('#' * 50) 297 update_test() 298 fetchall_test() 299 print('#' * 50) 300 delete_test() 301 fetchall_test() 302 303 if __name__ == '__main__': 304 main()
浙公网安备 33010602011771号