Python版SQLite数据库操作类

#coding=gbk

import sqlite3


#数据库文件路径

path = "test.db"


#以字典形式输出字段

def dict_factory(cursor, row):

d = {}

for idx, col in enumerate(cursor.description):

d[col[0]] = row[idx]

return d


#获取数据库连接

def GetConn():

conn = sqlite3.connect(path)

conn.row_factory = dict_factory

return conn


#执行简单查询

def Query(sql):

conn = GetConn()

cursor = conn.cursor()

cursor.execute(sql)

result = cursor.fetchall()

cursor.close()

conn.close()

return result


#执行带参数的查询

def QueryWithParms(sql,parms):

conn = GetConn()

cursor = conn.cursor()

cursor.execute(sql,parms)

result = cursor.fetchall()

cursor.close()

conn.close()

return result


#执行简单SQL

def ExecSQL(sql):

conn = GetConn()

cursor = conn.cursor()

cursor.execute(sql)

conn.commit()

cursor.close()

conn.close()

return cursor.rowcount


#执行带参数的SQL

def ExecSQLWithParms(sql,parms):

conn = GetConn()

cursor = conn.cursor()

cursor.execute(sql,parms)

conn.commit()

cursor.close()

conn.close()

return cursor.rowcount


#执行多参数的SQL

def ExecSQLMany(sql,parms):

conn = GetConn()

cursor = conn.cursor()

cursor.executemany(sql,parms)

conn.commit()

cursor.close()

conn.close()

return cursor.rowcount



#调用事例

# import SQLiteHelper

# import datetime


#执行简单查询和带参数的查询

# result = SQLiteHelper.Query("select * from t1 where id = 1")

# result = SQLiteHelper.Query("select * from t1 where name like '%张%'")

# result = SQLiteHelper.QueryWithParms("select * from t1 where name like ?",('%张%',))

# result = SQLiteHelper.QueryWithParms("select * from t1 where id = ?",(1,))

# result = SQLiteHelper.QueryWithParms("select * from t1 where id in (?,?,?,?)",(2,3,4,5,))

# for row in result:

#     print(row["id"])

#     print(row["name"])

#     print(row["addtime"],"\n")

#     print(datetime.datetime.strptime(row["addtime"],"%Y-%m-%d %H:%M:%S"),"\n")


#执行简单SQL

# row = SQLiteHelper.ExecSQL("insert into t1(name,addtime) values('小丁','2018-09-18')")

# print(row)


#执行带参数的SQL

# parms = ('韩梅梅','2018-09-18')

# row = SQLiteHelper.ExecSQLWithParms("insert into t1(name,addtime) values(?,?)",parms)

# print(row)


#执行多参数的SQL

# parms = (('雷锋','2018-09-18'),('小丁','2018-09-19'),('小胡','2018-09-20'))

# row = SQLiteHelper.ExecSQLMany("insert into t1(name,addtime) values(?,?)",parms)

# print(row)


源码下载:SQLiteHelper.zip

  1. 本网站所收集的部分资料来源于互联网,本站不对其真实性负责,也不构成任何其他建议。如果您发现有侵犯您权益的内容,请与我们取得联系,我们会及时修改或删除。
  2. 传递知识、传递力量,欢迎各位网友对本站的文章进行转载和分享。
  3. 本站QQ群交流群:904314688  群号:904314688
发表评论
 
评论列表(目前共有 条评论)
暂时还没有评论哦~

文章搜索

商家广告


版权所有:秋风雅居 (www.198933.com) ©2024 All Rights Reserved.

粤ICP备20031662号