1.python中如何sqlite
下面的示例是通过拼接sql语句,来使用sqlite数据的。
import sqlite3;del main(): dbpath="db\\test.db"; try: conn=sqlite3.connect(self.dbpath); except: pass; # read sqlite3 cur=self.conn.cursor(); sql='Select user,pwd,sex,address,birth,comment from t_user'; try: cur.execute(sql); except: pass; res=cur.fetchone(); res=cur.fetchall(); ''' for line in res: key1=res[0]; key2=res[1]; ''' cur.close(); self.conn.close(); #update insert sqlite3 try: conn=sqlite3.connect(self.dbpath); except: pass; sql=("update t_user set address='"+str(address)+",birth='"+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") "' where user="+str(user)) try: self.conn.execute(sql); self.conn.commit(); except: self.conn.close(); self.conn=sqlite3.connect(self.dbpath); cur.close(); self.conn.close();
2,.sqlalchemy的使用
ORM是对象关系模型,对数据库的操作,如果使用拼接sql语句,是非常低下的方式,容易出错,而且调试麻烦。下面我们介绍一种更好的操作方式,是通过python的一个模块叫sqlalchemy实现的。具体的网址如下:http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html
下面给出上面网址中的示例,保存成文件就可以运行:
from sqlalchemy import *db = create_engine('sqlite:///tutorial.db')db.echo = False # Try changing this to True and see what happens#metadata = BoundMetaData(db)metadata = MetaData(db)users = Table('users', metadata, Column('user_id', Integer, primary_key=True), Column('name', String(40)), Column('age', Integer), Column('password', String),)users.create()i = users.insert()i.execute(name='Mary', age=30, password='secret')i.execute({'name': 'John', 'age': 42}, {'name': 'Susan', 'age': 57}, {'name': 'Carl', 'age': 33})#如果表已经存在,可以通过下面获取表对象#users = Table('users',metadata,autoload=True)s = users.select()rs = s.execute()row = rs.fetchone()print 'Id:', row[0]print 'Name:', row['name']print 'Age:', row.ageprint 'Password:', row[users.c.password]for row in rs: print row.name, 'is', row.age, 'years old'