This article illustrates the method of Python3 to realize the connection of SQLite database, which has good reference value for Python learning. Share for everyone to use for reference. The specific methods are as follows:
The instance code is as follows:
Import sqlite3
db = r "D:\pyWork\test.db" #pyWork目录下test. db database file
drp_tb_sql = "DROP table if exists staff" C4/>crt_tb_sql = "" "
create table if not EXISTS staff (
ID integer primary key autoincrement unique NOT NULL,
n Ame varchar (m), City
varchar ()
);
"" #连接数据库
con = sqlite3.connect (db)
cur = con.cursor ()
#创建表staff
cur.execute (drp_tb_sql)
Cur.execute (crt_tb_sql)
#插入记录
insert_sql = "INSERT into staff (name,city) VALUES (?,?)" # for Placeholder
Cur.execute (Insert_sql, (' Tom ', ' New York '))
Cur.execute (Insert_sql, (' Frank ', ' Los Angeles '))
Cur.execute (Insert_sql, (' Kate ', ' Chicago '))
Cur.execute (Insert_sql, (' Thomas ', ' Houston '
)) Cur.execute (Insert_sql, (' Sam ', ' Philadelphia '))
con.commit ()
#查询记录
select_sql = "SELECT * FROM Staff"
Cur.execute (select_sql)
#返回一个list, the object type in the list is tuple (tuple)
date_set = Cur.fetchall () for
row in Date_set:
print (Row)
cur.close ()
con.close ()
I hope this example will help you with your Python learning.