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

你可能感兴趣的:(Python,sqlite,python,sql,user,insert,import)