python连接sqlite数据库的代码_Python3实现连接SQLite数据库的方法
本文實例講述了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í)有所幫助。
總結(jié)
以上是生活随笔為你收集整理的python连接sqlite数据库的代码_Python3实现连接SQLite数据库的方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: anaconda matplotlib
- 下一篇: python接口和抽象类的区别_接口和抽