SQLite3
# SQLite3 嵌入式 数据库 python内置SQLite3 # 导入驱动 import sqlite3 # 创建自增主键的表 msql = "create table user (id integer primary key ,name varchar (20),password varchar (20))" # 新增数据 msql2 = "insert into user (name,password) values ('Tom','xxxxx')" # 更新数据 msql3 = "update user set name ='LiLei' where id = 1" # 查询数据 msql4 = "select id,name,password from user " msql5 = "delete from user where name = "Tom"" import sys # 初始化数据库 def InIt_Database(): print("==========初始化数据库") # 连接数据库 若不存在 则自动创建 mConnection = sqlite3.connect("testsqlite3.db") mCursor = mConnection.cursor() try: mCursor.execute(msql) except: # sys.exc_info()会返回一个3值原表(type,value,traceback) print("数据库已经存在 不可重复创建 异常信息 ERROR=", sys.exc_info()[1]) finally: mConnection.commit() mCursor.close() mConnection.close() print("==========初始化数据库结束") def Insert_test(msql): print("==========新增数据") # 连接数据库 若不存在 则自动创建 mConnection = sqlite3.connect("testsqlite3.db") mCursor = mConnection.cursor() mCursor.execute(msql) mConnection.commit() print("新增一条数据 返回行数:", mCursor.rowcount) mCursor.execute(msql4) print("==========查询数据库") for row in mCursor: print("ID=%s,Name=%s"%(row[0],row[1])) mConnection.commit() mCursor.close() mConnection.close() def Update_test(msql): # 连接数据库 若不存在 则自动创建 mConnection = sqlite3.connect("testsqlite3.db") mCursor = mConnection.cursor() mCursor.execute(msql) mConnection.commit() mCursor.execute(msql4) for row in mCursor: print("ID=%s,Name=%s"%(row[0],row[1])) mConnection.commit() mCursor.close() mConnection.close() def Delete_test(msql): # 连接数据库 若不存在 则自动创建 mConnection = sqlite3.connect("testsqlite3.db") mCursor = mConnection.cursor() mCursor.execute(msql) mConnection.commit() mCursor.execute(msql4) for row in mCursor: print("ID=%s,Name=%s"%(row[0],row[1])) mConnection.commit() mCursor.close() mConnection.close() InIt_Database() Insert_test(msql2) Update_test(msql3) Delete_test(msql5)