Python 如何使用SQLite資料庫

2021-07-26 12:31:31 字數 2922 閱讀 7012

在資料庫支援方面,python提供了很簡便的介面,可以很容易地連線到mysql、sqlite等各種各樣的資料庫。

sqlite是一種輕量化的檔案型資料庫,預設是直接使用檔案的形式在本地計算機就可以直接擁有運算元據庫的優勢。也就說,雖然sqlite把資料庫以檔案的形式表現,但具有資料庫的操作功能,通過sql指令,進行選擇、插入、更新和刪除的操作。

1、sqlite資料庫的建立

可以利用視覺化的工具,如firefox 的sqlite  manager附加元件,進行建立。

2、sqlite資料庫的使用

在python中使用sqlite資料庫,需要以下幾個關鍵步驟:

3、sqlite資料庫的操作例項

----------用門市銷售管理的入庫、庫存整理、銷售、檢視庫存分別進行資料庫的插入(insert)、更新(update)、刪除(delete)和選擇(selete)操作。

import sqlite3

#顯示專案選單

def display_menu():

print("門市銷售")

print("---------------------------")

print("1.入庫")

print("2.整理")

print("3.銷售")

print("4.顯示所有庫存")

print("0.退出")

print("---------------------------")

#入庫 while true:

goodsnumber = int(input("請輸入商品編號(-1停止輸入):"))

if goodsnumber == -1: break

name = input("請輸入商品名稱:")

sqlstr = "select * from goods where goods_no={};".format(goodsnumber)

cursor = conn.execute(sqlstr)

if len(cursor.fetchall()) > 0:

print("你輸入的商品編號已經有資料了")

else:

sqlstr = \

"insert into goods values({},'{}');"\

.format(goodsnumber,name)

conn.execute(sqlstr)

conn.commit()

#整理def update_data():

sqlstr = \

"select * from goods where goods_no={};".format(goodsnumber)

cursor = conn.execute(sqlstr)

rows = cursor.fetchall()

if len(rows) > 0:

print("當前的商品名稱:",rows[0][1])

name = input("請輸入商品名稱:")

sqlstr = \

"update goods set name ='{}' where goods_no={};".format(name, goodsnumber)

conn.execute(sqlstr)

conn.commit()

else:

print("找不到要整理的商品編號!")

#銷售def sales_data():

goodsnumber = input("請輸入要銷售的產品編號:")

sqlstr = "select * from goods where goods_no={};".format(goodsnumber)

cursor = conn.execute(sqlstr)

rows = cursor.fetchall()

if len(rows) > 0:

print("你當前要銷售的產品編號{}的{}".format(rows[0][0], rows[0][1]))

answer = input("確定要銷售嗎?(y/n)")

if answer == 'y' or answer == 'y':

sqlstr = "delete from goods where goods_no={};".format(goodsnumber)

conn.execute(sqlstr)

conn.commit()

print("已銷售指定的商品...")

else:

print("找不到要銷售的商品!")

#顯示庫存

def display_data():

cursor = conn.execute('select * from goods;')

for row in cursor:

print("商品編號:{}: {}".format(row[0], row[1]))

conn = sqlite3.connect('d:\pythontest\salesmanager_db.sqlite')

while true:

display_menu()

choice = int(input("請輸入你的選擇:"))

if choice == 0:

conn.close()

break

if choice == 1:

elif choice == 2:

update_data()

elif choice == 3:

sales_data()

elif choice == 4:

display_data()

else:break

x = input("請按enter鍵返回主選單")

android中使用adb檢視sqlite資料庫

1.進入到控制台中,輸入adb shell,進入到命令模式的環境中 2.輸入cd data data 轉換到專案資料夾 3.選擇的專案檔案,比如我的com.android.homework,輸入命令 cd com.android.homework 4.可以使用ls l 命令檢視當前目錄中的檔案 5....

如何在PHP5中通過PDO連線SQLite3資料庫

如何在php5中通過pdo連線sqlite3資料庫 通過php 跟pdo 配置sqlite 資料庫是一件很繁瑣的事情,經過一下午的研究,終於理清了裡面的思路。現在拿出來跟大家共享。初學,錯誤請指出。首先我們先選擇要使用的 web server 軟體,由於從相容性跟效能方面的需求,我選擇了目前來說最新...

Python儲存二進位制資料到sqlite3

我們有這樣乙個需求 要儲存二進位制檔案到資料庫,以後還要從資料庫讀出來使用。到網上g了一下,發現可以實現,記錄以備忘。coding utf8 python2.6.2 import sqlite3 db sqlite3.connect test.db cur db.cursor cur.execute...