1. 程式人生 > >sqlite3在python中的入門

sqlite3在python中的入門

import sqlite3

def sqlite3_create_table(chart, key_attr, attr):
    # command='create table Book ( id varchar(20) primary key, veges varchar(30))'
command = 'CREATE TABLE ' + chart + '( ' + key_attr + 'VARCHAR(20) PRIMARY KEY, ' + attr + ' VARCHAR(30))'
cur.execute(command)
    con.commit()


def sqlite3_insert
(chart, attr1, attr2, attr1_value_str, attr2_value_str): # 暫定兩個引數 # command='Insert into Book ( id, veges) values ( "apple" ,"ba")' command = 'Insert INTO ' + chart + '(' + attr1 + ', ' + attr2 + ') Values("' + attr1_value_str + '","' + attr2_value_str + '")' print(command) cur.execute(command) con.commit() def
sqlite3_delete(chart, attr, attr_value_str): # 暫定一個引數 # command='delete from Book where id = "apple"' command = 'delete from ' + chart + ' where ' + attr + '=' + attr_value_str + '"' print(command) cur.execute(command) con.commit() def sqlite3_update(chart, new_attr, new_attr_value, old_attr,
old_attr_value): # 暫定根據一個引數改一個引數 # command="update Book set id ='pair' where id ='apple'" command = 'update ' + chart + ' set ' + new_attr + '= "' + new_attr_value + '" where ' + old_attr + '="' + old_attr_value + '"' print(command) cur.execute(command) con.commit() def sqlite3_find(chart): # command='select * from Book' command = "select * from " + chart print(command) cur.execute(command) con.commit() def connect_db3(path=r'd:/sqlite3data/mydatabase.db3'): con = sqlite3.connect(path) cur = con.cursor() return con, cur def close_db3(con, cur): cur.close() con.close() con, cur = connect_db3() chart = "test" key_attr = "num" attr = "sex" try: sqlite3_create_table(chart, key_attr, attr) except: print("faild") try: sqlite3_insert(chart, key_attr, attr, "nihao", "nibuhao") except: print("faild") cur.execute('SELECT * FROM foo3') print(cur.fetchall()) close_db3(con, cur)