python鏈接sqlite數(shù)據(jù)庫的詳細(xì)代碼實(shí)例
一、創(chuàng)建數(shù)據(jù)庫
創(chuàng)建sqlite數(shù)據(jù)庫的代碼
import sqlite3 conn = sqlite3.connect("test.db") print("成功創(chuàng)建數(shù)據(jù)庫")
運(yùn)行代碼后左側(cè)文件欄中會出現(xiàn)“test.db”文件,
二、鏈接數(shù)據(jù)庫
視圖->工具窗口->Database
此時編輯器右側(cè)出現(xiàn)Database,點(diǎn)擊添加按鈕
點(diǎn)擊路徑選擇按鈕,找到創(chuàng)建好的“test.db”文件,選中
注意:Download下載時,可能會提示下載失敗,多試兩次總會下載下來
此時就將數(shù)據(jù)庫鏈接好了
三、數(shù)據(jù)庫的增刪與查找
1、添加表頭
c = conn.cursor() #獲取游標(biāo) 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() #關(guān)閉數(shù)據(jù)庫鏈接 print("成功建表")
2、插入數(shù)據(jù)
conn = sqlite3.connect("test.db") print("成功打開數(shù)據(jù)庫") c = conn.cursor() #獲取游標(biāo) 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() #關(guān)閉數(shù)據(jù)庫鏈接 print("成功插入數(shù)據(jù)")
3、查找數(shù)據(jù)
conn = sqlite3.connect("test.db") print("成功打開數(shù)據(jù)庫") c = conn.cursor() # 獲取游標(biāo) 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() # 關(guān)閉數(shù)據(jù)庫鏈接 print("成功查找數(shù)據(jù)")
四、運(yùn)行結(jié)果
控制臺打印數(shù)據(jù)
數(shù)據(jù)庫表內(nèi)容
到此這篇關(guān)于python鏈接sqlite數(shù)據(jù)庫的詳細(xì)代碼實(shí)例的文章就介紹到這了,更多相關(guān)python 鏈接sqlite內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。