你的位置:首页 > 数据库

[数据库]python 之 sqlite3


 1 # -*- coding: utf-8 -*- 2 ''' 创建数据库日志,三列为时间 身份证号和备注名''' 3 import os  4 import sys  5 import sqlite3 6 import datetime  7  8  9 class sqlite3_log():10   11   def __init__(self):12     pass13   14   #连接表,表名为参15   def connect_db(self,db_name): 16     conn = sqlite3.connect(db_name) 17     return conn18    19   #关闭连接,表名为参20   def close_db(self,conn): 21     conn.close() 22 23   #建立一个表 表名应该使用参数确定24   def create_table(self,conn,table_name): 25     cu = conn.cursor() 26     cu.execute('''create table if not exists %s27           (time_now   text  primary key  not null,28            id_card  float     not null,29            name   text      not null);''' %table_name)30     conn.commit()31     32   #插入数据33   def insert_values(self, table_name, datetime, idcard, name):34     cu = conn.cursor()35     cu.execute("insert into %s values ( ?, ?, ?)" %table_name, (datetime, idcard, name))36     conn.commit() 37    38    39   #查询表是否存在40   def query_table(conn,db_name,table_name): 41     cu = conn.cursor() 42     cu.execute("select %s from %s where type = 'table' " %db_name, table_name )43     return cu.fetchall()44   45   #逻辑流程46   def run_log(self, db_name, table_name, tim, idcard, name):47     global conn48     #检测数据库表是否存在49     if os.path.exists(db_name):50       print "the table is exists"51       conn = sqlite3.connect(db_name)52     53     else:54       print "######"55       conn = self.connect_db(db_name)56       57     #检测表是否存在并创建表58     print "create table if not exists"59     self.create_table(conn, table_name)60     print "create table-conn"61     #a = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')62     print "insert finished"63     self.insert_values(table_name, tim, idcard, name)64     #关闭连接65     self.close_db(conn)66     67  68 def test():69   #测试代码70   db_name = './Peeer.db' 71   a = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')72   g = "wei"73   #print time174   sq = sqlite3_log()75   conn = sq.connect_db(db_name)76   #sq.create_table(conn, "talbe_sqlite")77   78   sq.insert_values("talbe_sqlite" , a , "05411722444554148763", g)79   sq.insert_values("talbe_sqlite" , a, "01444122274444115", "guo")80   sq.close_db(conn)81 82 if __name__ == '__main__':83   #测试逻辑流程84   sq = sqlite3_log()85   a = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')86   sq.run_log('./Peeeeer.db', "talbe_sqlite", a, "0144417722274444115", "guo")

  此代码已经测试,可以直接调用此类把数据写入。