您好,欢迎访问一九零五行业门户网

关于Python开发SQLite3数据库相关操作详解

这篇文章主要介绍了python开发sqlite3数据库相关操作,结合实例形式较为详细的分析了python操作sqlite3数据库的连接,查询,插入,更新,删除,关闭等相关操作技巧,需要的朋友可以参考下
本文实例讲述了python开发sqlite3数据库相关操作。分享给大家供大家参考,具体如下:
'''sqlite数据库是一款非常小巧的嵌入式开源数据库软件,也就是说 没有独立的维护进程,所有的维护都来自于程序本身。 在python中,使用sqlite3创建数据库的连接,当我们指定的数据库文件不存在的时候 连接对象会自动创建数据库文件;如果数据库文件已经存在,则连接对象不会再创建 数据库文件,而是直接打开该数据库文件。 连接对象可以是硬盘上面的数据库文件,也可以是建立在内存中的,在内存中的数据库 执行完任何操作后,都不需要提交事务的(commit) 创建在硬盘上面: conn = sqlite3.connect('c:\\test\\test.db') 创建在内存上面: conn = sqlite3.connect('"memory:') 下面我们一硬盘上面创建数据库文件为例来具体说明: conn = sqlite3.connect('c:\\test\\hongten.db') 其中conn对象是数据库链接对象,而对于数据库链接对象来说,具有以下操作: commit() --事务提交 rollback() --事务回滚 close() --关闭一个数据库链接 cursor() --创建一个游标 cu = conn.cursor() 这样我们就创建了一个游标对象:cu 在sqlite3中,所有sql语句的执行都要在游标对象的参与下完成 对于游标对象cu,具有以下具体操作: execute() --执行一条sql语句 executemany() --执行多条sql语句 close() --游标关闭 fetchone() --从结果中取出一条记录 fetchmany() --从结果中取出多条记录 fetchall() --从结果中取出所有记录 scroll() --游标滚动 '''
下面是我做的demo,在demo中,我做了很详细的注释和功能的演示,详情如下:
当show_sql = false的时候:
python 3.3.2 (v3.3.2:d047928ae3f6, may 16 2013, 00:03:43) [msc v.1600 32 bit (intel)] on win32 type "copyright", "credits" or "license()" for more information. >>> ================================ restart ================================ >>> show_sql : false 删除数据库表测试... 硬盘上面:[c:\test\hongten.db] 删除数据库表[student]成功! 创建数据库表测试... 硬盘上面:[c:\test\hongten.db] 创建数据库表[student]成功! 保存数据测试... 硬盘上面:[c:\test\hongten.db] 查询所有数据... 硬盘上面:[c:\test\hongten.db] (1, 'hongten', '男', 20, '广东省广州市', '13423****62') (2, 'tom', '男', 22, '美国旧金山', '15423****63') (3, 'jake', '女', 18, '广东省广州市', '18823****87') (4, 'cate', '女', 21, '广东省广州市', '14323****32') ################################################## 查询一条数据... 硬盘上面:[c:\test\hongten.db] (1, 'hongten', '男', 20, '广东省广州市', '13423****62') ################################################## 更新数据... 硬盘上面:[c:\test\hongten.db] 查询所有数据... 硬盘上面:[c:\test\hongten.db] (1, 'hongtenaa', '男', 20, '广东省广州市', '13423****62') (2, 'hongtenbb', '男', 22, '美国旧金山', '15423****63') (3, 'hongtencc', '女', 18, '广东省广州市', '18823****87') (4, 'hongtendd', '女', 21, '广东省广州市', '14323****32') ################################################## 删除数据... 硬盘上面:[c:\test\hongten.db] 查询所有数据... 硬盘上面:[c:\test\hongten.db] (2, 'hongtenbb', '男', 22, '美国旧金山', '15423****63') (4, 'hongtendd', '女', 21, '广东省广州市', '14323****32') >>>
当show_sql = true的时候:
python 3.3.2 (v3.3.2:d047928ae3f6, may 16 2013, 00:03:43) [msc v.1600 32 bit (intel)] on win32 type "copyright", "credits" or "license()" for more information. >>> ================================ restart ================================ >>> show_sql : true 删除数据库表测试... 硬盘上面:[c:\test\hongten.db] 执行sql:[drop table if exists student] 删除数据库表[student]成功! 创建数据库表测试... 硬盘上面:[c:\test\hongten.db] 执行sql:[create table `student` ( `id` int(11) not null, `name` varchar(20) not null, `gender` varchar(4) default null, `age` int(11) default null, `address` varchar(200) default null, `phone` varchar(20) default null, primary key (`id`) )] 创建数据库表[student]成功! 保存数据测试... 硬盘上面:[c:\test\hongten.db] 执行sql:[insert into student values (?, ?, ?, ?, ?, ?)],参数:[(1, 'hongten', '男', 20, '广东省广州市', '13423****62')] 执行sql:[insert into student values (?, ?, ?, ?, ?, ?)],参数:[(2, 'tom', '男', 22, '美国旧金山', '15423****63')] 执行sql:[insert into student values (?, ?, ?, ?, ?, ?)],参数:[(3, 'jake', '女', 18, '广东省广州市', '18823****87')] 执行sql:[insert into student values (?, ?, ?, ?, ?, ?)],参数:[(4, 'cate', '女', 21, '广东省广州市', '14323****32')] 查询所有数据... 硬盘上面:[c:\test\hongten.db] 执行sql:[select * from student] (1, 'hongten', '男', 20, '广东省广州市', '13423****62') (2, 'tom', '男', 22, '美国旧金山', '15423****63') (3, 'jake', '女', 18, '广东省广州市', '18823****87') (4, 'cate', '女', 21, '广东省广州市', '14323****32') ################################################## 查询一条数据... 硬盘上面:[c:\test\hongten.db] 执行sql:[select * from student where id = ? ],参数:[1] (1, 'hongten', '男', 20, '广东省广州市', '13423****62') ################################################## 更新数据... 硬盘上面:[c:\test\hongten.db] 执行sql:[update student set name = ? where id = ? ],参数:[('hongtenaa', 1)] 执行sql:[update student set name = ? where id = ? ],参数:[('hongtenbb', 2)] 执行sql:[update student set name = ? where id = ? ],参数:[('hongtencc', 3)] 执行sql:[update student set name = ? where id = ? ],参数:[('hongtendd', 4)] 查询所有数据... 硬盘上面:[c:\test\hongten.db] 执行sql:[select * from student] (1, 'hongtenaa', '男', 20, '广东省广州市', '13423****62') (2, 'hongtenbb', '男', 22, '美国旧金山', '15423****63') (3, 'hongtencc', '女', 18, '广东省广州市', '18823****87') (4, 'hongtendd', '女', 21, '广东省广州市', '14323****32') ################################################## 删除数据... 硬盘上面:[c:\test\hongten.db] 执行sql:[delete from student where name = ? and id = ? ],参数:[('hongtenaa', 1)] 执行sql:[delete from student where name = ? and id = ? ],参数:[('hongtencc', 3)] 查询所有数据... 硬盘上面:[c:\test\hongten.db] 执行sql:[select * from student] (2, 'hongtenbb', '男', 22, '美国旧金山', '15423****63') (4, 'hongtendd', '女', 21, '广东省广州市', '14323****32') >>>
具体代码:
#python sqlite #author : hongten #create : 2013-08-09 #version: 1.0 #db-api 2.0 interface for sqlite databases import sqlite3 import os '''sqlite数据库是一款非常小巧的嵌入式开源数据库软件,也就是说 没有独立的维护进程,所有的维护都来自于程序本身。 在python中,使用sqlite3创建数据库的连接,当我们指定的数据库文件不存在的时候 连接对象会自动创建数据库文件;如果数据库文件已经存在,则连接对象不会再创建 数据库文件,而是直接打开该数据库文件。 连接对象可以是硬盘上面的数据库文件,也可以是建立在内存中的,在内存中的数据库 执行完任何操作后,都不需要提交事务的(commit) 创建在硬盘上面: conn = sqlite3.connect('c:\\test\\test.db') 创建在内存上面: conn = sqlite3.connect('"memory:') 下面我们一硬盘上面创建数据库文件为例来具体说明: conn = sqlite3.connect('c:\\test\\hongten.db') 其中conn对象是数据库链接对象,而对于数据库链接对象来说,具有以下操作: commit() --事务提交 rollback() --事务回滚 close() --关闭一个数据库链接 cursor() --创建一个游标 cu = conn.cursor() 这样我们就创建了一个游标对象:cu 在sqlite3中,所有sql语句的执行都要在游标对象的参与下完成 对于游标对象cu,具有以下具体操作: execute() --执行一条sql语句 executemany() --执行多条sql语句 close() --游标关闭 fetchone() --从结果中取出一条记录 fetchmany() --从结果中取出多条记录 fetchall() --从结果中取出所有记录 scroll() --游标滚动 ''' #global var #数据库文件绝句路径 db_file_path = '' #表名称 table_name = '' #是否打印sql show_sql = true def get_conn(path): '''获取到数据库的连接对象,参数为数据库文件的绝对路径 如果传递的参数是存在,并且是文件,那么就返回硬盘上面改 路径下的数据库文件的连接对象;否则,返回内存中的数据接 连接对象''' conn = sqlite3.connect(path) if os.path.exists(path) and os.path.isfile(path): print('硬盘上面:[{}]'.format(path)) return conn else: conn = none print('内存上面:[:memory:]') return sqlite3.connect(':memory:') def get_cursor(conn): '''该方法是获取数据库的游标对象,参数为数据库的连接对象 如果数据库的连接对象不为none,则返回数据库连接对象所创 建的游标对象;否则返回一个游标对象,该对象是内存中数据 库连接对象所创建的游标对象''' if conn is not none: return conn.cursor() else: return get_conn('').cursor() ############################################################### #### 创建|删除表操作 start ############################################################### def drop_table(conn, table): '''如果表存在,则删除表,如果表中存在数据的时候,使用该 方法的时候要慎用!''' if table is not none and table != '': sql = 'drop table if exists ' + table if show_sql: print('执行sql:[{}]'.format(sql)) cu = get_cursor(conn) cu.execute(sql) conn.commit() print('删除数据库表[{}]成功!'.format(table)) close_all(conn, cu) else: print('the [{}] is empty or equal none!'.format(sql)) def create_table(conn, sql): '''创建数据库表:student''' if sql is not none and sql != '': cu = get_cursor(conn) if show_sql: print('执行sql:[{}]'.format(sql)) cu.execute(sql) conn.commit() print('创建数据库表[student]成功!') close_all(conn, cu) else: print('the [{}] is empty or equal none!'.format(sql)) ############################################################### #### 创建|删除表操作 end ############################################################### def close_all(conn, cu): '''关闭数据库游标对象和数据库连接对象''' try: if cu is not none: cu.close() finally: if cu is not none: cu.close() ############################################################### #### 数据库操作crud start ############################################################### def save(conn, sql, data): '''插入数据''' if sql is not none and sql != '': if data is not none: cu = get_cursor(conn) for d in data: if show_sql: print('执行sql:[{}],参数:[{}]'.format(sql, d)) cu.execute(sql, d) conn.commit() close_all(conn, cu) else: print('the [{}] is empty or equal none!'.format(sql)) def fetchall(conn, sql): '''查询所有数据''' if sql is not none and sql != '': cu = get_cursor(conn) if show_sql: print('执行sql:[{}]'.format(sql)) cu.execute(sql) r = cu.fetchall() if len(r) > 0: for e in range(len(r)): print(r[e]) else: print('the [{}] is empty or equal none!'.format(sql)) def fetchone(conn, sql, data): '''查询一条数据''' if sql is not none and sql != '': if data is not none: #do this instead d = (data,) cu = get_cursor(conn) if show_sql: print('执行sql:[{}],参数:[{}]'.format(sql, data)) cu.execute(sql, d) r = cu.fetchall() if len(r) > 0: for e in range(len(r)): print(r[e]) else: print('the [{}] equal none!'.format(data)) else: print('the [{}] is empty or equal none!'.format(sql)) def update(conn, sql, data): '''更新数据''' if sql is not none and sql != '': if data is not none: cu = get_cursor(conn) for d in data: if show_sql: print('执行sql:[{}],参数:[{}]'.format(sql, d)) cu.execute(sql, d) conn.commit() close_all(conn, cu) else: print('the [{}] is empty or equal none!'.format(sql)) def delete(conn, sql, data): '''删除数据''' if sql is not none and sql != '': if data is not none: cu = get_cursor(conn) for d in data: if show_sql: print('执行sql:[{}],参数:[{}]'.format(sql, d)) cu.execute(sql, d) conn.commit() close_all(conn, cu) else: print('the [{}] is empty or equal none!'.format(sql)) ############################################################### #### 数据库操作crud end ############################################################### ############################################################### #### 测试操作 start ############################################################### def drop_table_test(): '''删除数据库表测试''' print('删除数据库表测试...') conn = get_conn(db_file_path) drop_table(conn, table_name) def create_table_test(): '''创建数据库表测试''' print('创建数据库表测试...') create_table_sql = '''create table `student` ( `id` int(11) not null, `name` varchar(20) not null, `gender` varchar(4) default null, `age` int(11) default null, `address` varchar(200) default null, `phone` varchar(20) default null, primary key (`id`) )''' conn = get_conn(db_file_path) create_table(conn, create_table_sql) def save_test(): '''保存数据测试...''' print('保存数据测试...') save_sql = '''insert into student values (?, ?, ?, ?, ?, ?)''' data = [(1, 'hongten', '男', 20, '广东省广州市', '13423****62'), (2, 'tom', '男', 22, '美国旧金山', '15423****63'), (3, 'jake', '女', 18, '广东省广州市', '18823****87'), (4, 'cate', '女', 21, '广东省广州市', '14323****32')] conn = get_conn(db_file_path) save(conn, save_sql, data) def fetchall_test(): '''查询所有数据...''' print('查询所有数据...') fetchall_sql = '''select * from student''' conn = get_conn(db_file_path) fetchall(conn, fetchall_sql) def fetchone_test(): '''查询一条数据...''' print('查询一条数据...') fetchone_sql = 'select * from student where id = ? ' data = 1 conn = get_conn(db_file_path) fetchone(conn, fetchone_sql, data) def update_test(): '''更新数据...''' print('更新数据...') update_sql = 'update student set name = ? where id = ? ' data = [('hongtenaa', 1), ('hongtenbb', 2), ('hongtencc', 3), ('hongtendd', 4)] conn = get_conn(db_file_path) update(conn, update_sql, data) def delete_test(): '''删除数据...''' print('删除数据...') delete_sql = 'delete from student where name = ? and id = ? ' data = [('hongtenaa', 1), ('hongtencc', 3)] conn = get_conn(db_file_path) delete(conn, delete_sql, data) ############################################################### #### 测试操作 end ############################################################### def init(): '''初始化方法''' #数据库文件绝句路径 global db_file_path db_file_path = 'c:\\test\\hongten.db' #数据库表名称 global table_name table_name = 'student' #是否打印sql global show_sql show_sql = true print('show_sql : {}'.format(show_sql)) #如果存在数据库表,则删除表 drop_table_test() #创建数据库表student create_table_test() #向数据库表中插入数据 save_test() def main(): init() fetchall_test() print('#' * 50) fetchone_test() print('#' * 50) update_test() fetchall_test() print('#' * 50) delete_test() fetchall_test() if __name__ == '__main__': main()
以上就是关于python开发sqlite3数据库相关操作详解的详细内容。
其它类似信息

推荐信息