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
在給出一個網址:http://docs.sqlalchemy.org/en/rel_0_7/core/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'
通過上面的代碼,相信大家都明白了,基本的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給合并,消除冗餘的代碼。