python鏈接sqlite數(shù)據(jù)庫的詳細代碼實例
一、創(chuàng)建數(shù)據(jù)庫
創(chuàng)建sqlite數(shù)據(jù)庫的代碼
import sqlite3
conn = sqlite3.connect("test.db")
print("成功創(chuàng)建數(shù)據(jù)庫")
運行代碼后左側文件欄中會出現(xiàn)“test.db”文件,

二、鏈接數(shù)據(jù)庫
視圖->工具窗口->Database

此時編輯器右側出現(xiàn)Database,點擊添加按鈕

點擊路徑選擇按鈕,找到創(chuàng)建好的“test.db”文件,選中


注意:Download下載時,可能會提示下載失敗,多試兩次總會下載下來
此時就將數(shù)據(jù)庫鏈接好了
三、數(shù)據(jù)庫的增刪與查找
1、添加表頭
c = conn.cursor() #獲取游標
sql = '''
create table company
(id int primary key not null,
name text not null,
age int not null,
address char(50),
salary real);
'''
c.execute(sql)#執(zhí)行sql語句
conn.commit() #提交數(shù)據(jù)庫操作
conn.close() #關閉數(shù)據(jù)庫鏈接
print("成功建表")
2、插入數(shù)據(jù)
conn = sqlite3.connect("test.db")
print("成功打開數(shù)據(jù)庫")
c = conn.cursor() #獲取游標
sql1 = '''
insert into company (id,name,age,address,salary)
values (1,'張三',32,"成都",8000);
'''
sql2 = '''
insert into company (id,name,age,address,salary)
values (2,'李四',30,"深圳",15000);
'''
c.execute(sql1) #執(zhí)行sql語句
c.execute(sql2)
conn.commit() #提交數(shù)據(jù)庫操作
conn.close() #關閉數(shù)據(jù)庫鏈接
print("成功插入數(shù)據(jù)")
3、查找數(shù)據(jù)
conn = sqlite3.connect("test.db")
print("成功打開數(shù)據(jù)庫")
c = conn.cursor() # 獲取游標
sql = '''
select id,name,address,salary from company
'''
cursor = c.execute(sql) # 執(zhí)行sql語句
for row in cursor:
print("id = ",row[0])
print("name = ",row[1])
print("address = ",row[2])
print("salary = ",row[3],"\n")
conn.close() # 關閉數(shù)據(jù)庫鏈接
print("成功查找數(shù)據(jù)")
四、運行結果
控制臺打印數(shù)據(jù)

數(shù)據(jù)庫表內(nèi)容

到此這篇關于python鏈接sqlite數(shù)據(jù)庫的詳細代碼實例的文章就介紹到這了,更多相關python 鏈接sqlite內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持本站!
版權聲明:本站文章來源標注為YINGSOO的內(nèi)容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。
關注官方微信