当前位置:Gxlcms > 数据库问题 > Python之sqlite3

Python之sqlite3

时间:2021-07-01 10:21:17 帮助过:35人阅读

coding=utf-8 import sqlite3 conn = sqlite3.connect("sqlite.db") #创建sqlite.db数据库 print ("open database success") conn.execute("drop table IF EXISTS student") query = """create table IF NOT EXISTS student( customer VARCHAR(20), produce VARCHAR(40), amount FLOAT, date DATE );""" conn.execute(query) print ("Table created successfully") #在表中插入数据 ‘‘‘ 方法1 ‘‘‘ #data = ‘‘‘INSERT INTO student(customer,produce,amount,date)\ # VALUES("zhangsan","notepad",999,"2017-01-02")‘‘‘ #conn.execute(data) #data = ‘‘‘INSERT INTO student(customer,produce,amount,date)\ # VALUES("lishi","binder",3.45,"2017-04-05")‘‘‘ #conn.execute(data) #conn.commit() ‘‘‘ 方法2 ‘‘‘ statement = "INSERT INTO student VALUES(?,?,?,?)" data = [("zhangsan","notepad",999,"2017-01-02"),("lishi","binder",3.45,"2017-04-05")] conn.executemany(statement, data) conn.commit() curson = conn.execute("select * from student") conn.commit() print (curson) rows = curson.fetchall() print (rows) conn.close()

sqlite3 csv->db->csv

‘‘‘将csv数据导入数据库‘‘‘
import sys
import csv
import sqlite3

#解析csv文件
def parsecsvFile(filepath):
    header = None
    data = []
    with open(filepath, r) as csvfile:
        filereader = csv.reader(csvfile)
        header = next(filereader)
        #print (header)
        for row in filereader:
            data.append(row)
        #print (data)
    return header,data

#使用sqlite3写数据库
def initdb(header, data):
    conn = sqlite3.connect("sqlite.db")
    print ("connect database success")
    conn.execute("drop table IF EXISTS student")
    conn.commit()
    query = ‘‘‘create table IF NOT EXISTS student(        Supplier Name VARCHAR(32),
        Invoice Number VARCHAR(16),
        Part Number VARCHAR(16),
        Cost VARCHAR(16),
        Purchase Date DATE);‘‘‘
    conn.execute(query)
    conn.commit() 
    statement = "INSERT INTO student VALUES(?,?,?,?,?)"
    conn.executemany(statement, data)
    conn.commit()
    curson = conn.execute("select * from student")
    conn.commit()
    print (curson)
    rows = curson.fetchall()
    print (rows)
    conn.close()
    return rows

#根据数据库内容写csv文件
def wirtecsvfile(writefilepath, header, data):
    with open(writefilepath, a+) as writefile:
        writer = csv.writer(writefile, delimiter=",")
        writer.writerow(header)
        for row in data:
            writer.writerow(row)
    
if __name__ == "__main__":
    readfilepath = sys.argv[1]
    writefilepath = sys.argv[2]
    header,data = parsecsvFile(readfilepath)
    rows = initdb(header, data)
    wirtecsvfile(writefilepath, header, rows)

 

Python之sqlite3

标签:[]   pat   修改   san   查询   class   file   ecs   十分   

人气教程排行