社區(qū)版找不到數(shù)據(jù)庫,需要先安裝Database Navigator插件,之后才能通過sqlite3連接數(shù)據(jù)庫。
1、安裝Database Navigator
①文件 —> ②設(shè)置 —> ③插件 —> ④Marketplace搜索database —> ⑤安裝Database Navigator —> ⑥應(yīng)用確定
安裝之后就可以在頁面左側(cè)邊欄找到DB Browser,也可以拖動(dòng)移動(dòng)到頁面右側(cè)。找不到的可以在視圖中打開。
2、創(chuàng)建數(shù)據(jù)庫
import sqlite3 # 導(dǎo)入sqlite3
conn = sqlite3.connect("test.db") # 打開或創(chuàng)建數(shù)據(jù)庫文件
print("Opened database successfully!")
運(yùn)行上述代碼之后左側(cè)同級(jí)目錄下會(huì)出現(xiàn)一個(gè)剛創(chuàng)建的數(shù)據(jù)庫文件test.db。
3、通過SQLite連接數(shù)據(jù)庫
點(diǎn)擊Database files右側(cè)的三個(gè)點(diǎn),選擇剛創(chuàng)建的數(shù)據(jù)庫文件test.db。
點(diǎn)擊Test Connection測(cè)試是否連接成功。連接成功,會(huì)出現(xiàn)下圖成功的標(biāo)識(shí)。
4、創(chuàng)建數(shù)據(jù)表
c = conn.cursor() # 獲取游標(biāo)
# 創(chuàng)建數(shù)據(jù)庫表頭
sql = '''
create table company
(id int primary key autoincrement,
name text not null,
age int not null,
address char(50),
salary real);
'''
c.execute(sql) # 執(zhí)行sql語句
運(yùn)行上述代碼,刷新右側(cè)Tables會(huì)出現(xiàn)一個(gè)新建的company數(shù)據(jù)表,表格里面有5個(gè)字段。文章來源:http://www.zghlxwxcb.cn/news/detail-795721.html
5、實(shí)現(xiàn)增刪改查
5.1、在表中插入數(shù)據(jù)
我們建表的時(shí)候設(shè)置了id屬性自增,所以插入數(shù)據(jù)不用填寫id值。文章來源地址http://www.zghlxwxcb.cn/news/detail-795721.html
# 插入數(shù)據(jù)
sql1 = '''
insert into company(name, age, address, salary)
VALUES ('張三', 28, "北京", 8000)
'''
sql2 = '''
insert into company(name, age, address, salary)
VALUES ('李四', 31, "西安", 5000)
'''
c.execute(sql1)
c.execute(sql2)
5.2、查找表中的數(shù)據(jù)
# 1、查找全部數(shù)據(jù)
sql3 = "select * from company"
# 2、查找某列數(shù)據(jù)
sql3 = "select name from company"
# 3、查找條件數(shù)據(jù)
sql3 = "select * from company where name = '李四'"
tem = c.execute(sql3)
for row in tem:
print(row)
5.3、刪除表中數(shù)據(jù)
# 1、刪除表中全部數(shù)據(jù)
sql4 = "delete from company"
c.execute(sql4)
# 2、刪除指定數(shù)據(jù)
sql5 = "delete from company where name = '張三'"
c.execute(sql5)
print("刪除成功")
5.4、修改表中數(shù)據(jù)
# 修改表中數(shù)據(jù)
sql6 = "update company set name = '小彭' where id = 1" # 將id=1的記錄的name屬性值改為“小彭”
c.execute(sql6)
到了這里,關(guān)于pycharm社區(qū)版使用SQLite連接數(shù)據(jù)庫,并實(shí)現(xiàn)數(shù)據(jù)的增刪改查的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!