python orm sqlite_Python中Sqlite的使用&ORM的使用&如何通过code初始化DB | 学步园

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.age

print 'Password:', row[users.c.password]

for row in rs:

print row.name, 'is', row.age, 'years old'

通过上面的代码,相信大家都明白了,基本的sqlalchemy是如何使用的。

3.工程里如何初始化数据库

在一个工程中,最好的方式是当工程开始的时候,通过代码的形式创建并检测数据库,如果数据库不存在则创建数据库,如果数据库中缺少表,则创建该表。下面是一个牛人给我修改过的代码,代码中我给了注释:

from sqlalchemy import *

global_table_list = (

('t_table1', (

Column('c_id',Integer,Sequence('t_table1_id_seq'),primary_key=True),

Column('c_name', String(40)),

Column('c_keywords', Text),

Column('c_time', TIMESTAMP),

Column('c_status', Integer),

Column('c_comment', String(20)),

)

),

('t_table2', (

Column('c_id',Integer,Sequence('t_table2_id_seq'),primary_key=True),

Column('c_type', Integer),

Column('c_sex', BOOLEAN),

Column('c_province', Integer),

Column('c_area', Integer),

Column('c_platform', String(40)),

Column('c_url', String(100)),

)

),

('t_table3', (

Column('c_rule_id',Integer),

Column('c_keyword', String(40)),

Column('c_timeline', String(20)),

)

),

)

def init_db():

db = create_engine('sqlite:///test.db')

db.echo = False # Try changing this to True and see what happens

metadata = MetaData(db)

for (t_name,t_columns) in global_table_list:

try:

cur_table = Table(t_name,metadata,autoload=True)

except:

#下面这句等价于:cur_table = Table(t_name,metadata,t_columns)

#apply表示调用函数,这里是调用函数Table()

#apply的调用形式如下,apply(func_name,args),apply的第二个参数args要是列表的形式

#所以,这里args是个参数列表,要以(arg1,arg2,...)的形式调用

cur_table = apply(Table,(t_name,metadata) + t_columns)

cur_table.create()

if __name__ == '__main__':

init_db()

下面简单讲解一下:首先将表的名称和结构保存在list中;create_engine方法可以判断数据库是否存在,当数据库文件存在时,则调用该数据库,当数据库不存在时,则会自动创建数据库文件;然后,通过一个循环遍历list,检测表是否存在,如果不存在则创建。

这里用到了python中的一个系统函数apply,通过apply可以调用系统函数。如下所示:apply(func,args)。 比如函数 fun_abc(str1,str2,str3)。通过apply调用,则为apply(fun_abc,(str1,str2,str3)),即args为一个list:(str1,str2,str3)。

再给出一个我最初的写法,很低级:

from sqlalchemy import *

def init_db():

db = create_engine('sqlite:///test.db')

db.echo = False # Try changing this to True and see what happens

metadata = MetaData(db)

#检测表t_table1

flag_table1 = True

try:

table1 = Table('t_table1',metadata,autoload=True)

except:

flag_table1 = False

if not flag_table1:

#create t_table1 table

table1 = Table('t_table1', metadata,

Column('c_id',Integer,Sequence('t_table1_id_seq'),primary_key=True),

Column('c_name', String(40)),

Column('c_keywords', Text),

Column('c_time', TIMESTAMP),

Column('c_status', Integer),

Column('c_comment', String(20)),

)

table1.create()

#检测表t_table2

flag_table2 = True

try:

table2 = Table('t_table2',metadata,autoload=True)

except:

flag_table2 = False

if not flag_table2:

#create t_table2 table

table2 = Table('t_table2', metadata,

Column('c_id',Integer,Sequence('t_table2_id_seq'),primary_key=True),

Column('c_type', Integer),

Column('c_sex', BOOLEAN),

Column('c_province', Integer),

Column('c_area', Integer),

Column('c_platform', String(40)),

Column('c_url', String(100)),

)

table2.create()

#检测表t_table3

flag_table3 = True

try:

table3 = Table('t_table3',metadata,autoload=True)

except:

flag_table3 = False

if not flag_table3:

#create t_table3 table

table3 = Table('t_table3', metadata,

Column('c_rule_id',Integer),

Column('c_keyword', String(40)),

Column('c_timeline', String(20)),

)

table3.create()

if __name__ == '__main__':

init_db()

通过这两段code,我想说的是:好的code,一定要把结构相同的code给合并,消除冗余的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值