本文實例講述了Python3實現(xiàn)連接SQLite數(shù)據(jù)庫的方法,對于Python的學(xué)習(xí)有不錯的參考借鑒價值。分享給大家供大家參考之用。具體方法如下:
實例代碼如下:
import sqlite3
db = r"D:\pyWork\test.db" #pyWork目錄下test.db數(shù)據(jù)庫文件
drp_tb_sql = "drop table if exists staff"
crt_tb_sql = """
create table if not exists staff(
id integer primary key autoincrement unique not null,
name varchar(100),
city varchar(100)
);
"""
#連接數(shù)據(jù)庫
con = sqlite3.connect(db)
cur = con.cursor()
#創(chuàng)建表staff
cur.execute(drp_tb_sql)
cur.execute(crt_tb_sql)
#插入記錄
insert_sql = "insert into staff (name,city) values (?,?)" #?為占位符
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,list中的對象類型為tuple(元組)
date_set = cur.fetchall()
for row in date_set:
print(row)
cur.close()
con.close()
希望本文實例對大家的Python學(xué)習(xí)有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

