最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python練習(xí)之操作SQLite數(shù)據(jù)庫

 更新時(shí)間:2022年06月13日 10:44:52   作者:? 孤寒者?  ?  
這篇文章主要介紹了Python練習(xí)之操作SQLite數(shù)據(jù)庫,主要通過三個(gè)問題如何創(chuàng)建SQLite數(shù)據(jù)庫?如何向SQLite表中插入數(shù)據(jù)?如何查詢SQLite表中的數(shù)據(jù)?展開文章主題詳情,需要的朋友可以參考一下

前言

文章包括下幾點(diǎn):

考點(diǎn)--操作SQLite數(shù)據(jù)庫:

  • 創(chuàng)建SQLite數(shù)據(jù)庫;
  • 向表中插入記錄;
  • 其他數(shù)據(jù)庫操作。

面試題:

  • 1.面試題一:如何創(chuàng)建SQLite數(shù)據(jù)庫?
  • 2.面試題二:如何向SQLite表中插入數(shù)據(jù)?
  • 3.面試題三:如何查詢SQLite表中的數(shù)據(jù)?

1.創(chuàng)建SQLite數(shù)據(jù)庫

# coding=utf-8
# _author__ = 孤寒者
import sqlite3
import os
dbPath = 'data.sqlite'
if not os.path.exists(dbPath):
    conn = sqlite3.connect(dbPath)
    c = conn.cursor()
    c.execute('''create table persons
              (id int primary key not null,
               name text not null,
               age int not null,
               address char(100),
               salary real);''')
    conn.commit()
    conn.close()
    print('創(chuàng)建數(shù)據(jù)庫成功')

  • 我們通過上述操作已經(jīng)成功創(chuàng)建了sql數(shù)據(jù)庫,并在里面創(chuàng)建了一張表。
  • 為了查看我們創(chuàng)建的表,我們可以用到SqliteStudio,它是一款 Sqlite數(shù)據(jù)庫可視化工具,是使用Sqlite數(shù)據(jù)庫開發(fā)應(yīng)用的必備軟件,軟件無需安裝,下載后解壓即可使用,很小巧但很了用,綠色中文版本。比起其它SQLite管理工具,我喜歡用這個(gè)。很方便易用,不用安裝的單個(gè)可執(zhí)行文件,支持中文。

2.向SQLite表中插入數(shù)據(jù)

# coding=utf-8
import sqlite3
dbPath = 'data.sqlite'
conn = sqlite3.connect(dbPath)
c = conn.cursor()
# 首先將表中數(shù)據(jù)全部刪除
c.execute('delete from persons')
# 插入數(shù)據(jù)
c.execute('''
insert into persons(id,name,age,address,salary)
values(1, '孤寒者', 18, 'China', 9999)
''')
c.execute('''
insert into persons(id,name,age,address,salary)
values(2, '小張', 55, 'China', 9)
''')
conn.commit()
print('insert success')

3.查詢SQLite表中的數(shù)據(jù)

# coding=utf-8
import sqlite3
dbPath = 'data.sqlite'
conn = sqlite3.connect(dbPath)
c = conn.cursor()
persons = c.execute('select name,age,address,salary from persons order by age')

# 打印查詢結(jié)果發(fā)現(xiàn)是個(gè)Cursor對象(可迭代對象)
print(type(persons))

result = []
for person in persons:
    value = {}
    value['name'] = person[0]
    value['age'] = person[1]
    value['address'] = person[2]
    result.append(value)
conn.close()
print(type(result))
print(result)

# 我們也可以使用前面學(xué)習(xí)的json模塊使這個(gè)list類型的result轉(zhuǎn)為字符串類型
# 網(wǎng)絡(luò)傳輸需要使用字符串類型
import json
resultStr = json.dumps(result, ensure_ascii=False)
print(resultStr)

總結(jié)

使用sqlite3模塊中的API可以操作SQLite數(shù)據(jù)庫,該模塊是Python內(nèi)置的模塊,不需要單獨(dú)安裝。

到此這篇關(guān)于Python練習(xí)之操作SQLite數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)Python操作SQLite 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

运城市| 余姚市| 瑞金市| 印江| 包头市| 乌兰察布市| 都昌县| 亳州市| 镇江市| 罗山县| 虎林市| 元江| 囊谦县| 中卫市| 泸水县| 三亚市| 东阳市| 通道| 桂平市| 台前县| 巢湖市| 会理县| 弥渡县| 新蔡县| 都安| 怀化市| 大石桥市| 伊宁市| 莒南县| 青海省| 永修县| 安多县| 浦城县| 泸西县| 运城市| 伊金霍洛旗| 清水河县| 防城港市| 宁武县| 通化县| 方正县|