Skip to content

Instantly share code, notes, and snippets.

@rswofxd
Created July 17, 2012 07:40
Show Gist options
  • Save rswofxd/3127840 to your computer and use it in GitHub Desktop.
Save rswofxd/3127840 to your computer and use it in GitHub Desktop.
Python://PySqlite3/Python对于Sqlite3数据库操作
#coding:utf-8
"""
Python-Sqlite3数据库操作
自定义数据类型存储
"""
import sqlite3
try:
import cPickle as pickle
except :
import pickle
db_filename='todo.db'
def adapter_func(obj):
"""
Convert from in-memory to storage representation
封装并存储数据
"""
print 'adapter_func(%s)n' % obj
return pickle.dumps(obj)
def converter_func(data):
"""
Convert from storage to in-memory representation
拆封并提取数据
"""
print 'converter_func(%s)' % data
return pickle.loads(data)
class MyObj(object):
"""
自定义数据类型
"""
def __init__(self,arg):
self.arg=arg
def __str__(self):
return 'MyObj(%s)' % self.arg
#Register the function for manipulating the type
sqlite3.register_adapter(MyObj,adapter_func)
sqlite3.register_converter("MyObj",converter_func)
#Create some object to save
to_save = [ (MyObj('this is a value to save'),),
(MyObj(42),),]
with sqlite3.connect(db_filename, detect_types=sqlite3.PARSE_DECLTYPES) as conn:
#Create a table with column of type 'MyObj'
#执行SQL语句
conn.execute("""
create table if not exists obj(id integer primary key autoincrement not null,
data MyObj)
""")
#创建游标对象
cursor=conn.cursor()
#Insert the objects into the database
#向obj表中插入数据
cursor.executemany("insert into obj (data) values (?)", to_save)
#Query the database for the object just saved
#从'obj'表中查询'id'键和'data'值
cursor.execute("select * from obj where id = 1")
print('========this is the id-data inquery========\n{}'.format(cursor.fetchone()))
#更新数据
#cursor.execute("update obj set data=MyObj(80) where id = 4")
#删除数据
cursor.execute("delete from obj where id = 5")
#从结果取出所有记录
cursor.execute("select id,data from obj")
for obj_id,obj in cursor.fetchall():
print 'Retrieved:',obj_id,obj,type(obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment