1. 程式人生 > 資料庫 >Python使用sqlite3模組內建資料庫

Python使用sqlite3模組內建資料庫

1、python內建的sqlite3模組,建立資料庫中的表,並向表中插入資料,從表中取出所有行,以及輸出行的數量。

#!/usr/bin/env python3
#建立SQLite3記憶體資料庫,並建立帶有四個屬性的sales表
#sqlite3模組,提供了一個輕量級的基於磁碟的資料庫,不需要獨立的伺服器程序
import sqlite3
#使用‘:memory:'在記憶體中建立了一個數據庫,建立了連線物件con來代表資料庫
con = sqlite3.connect(':memory:')
#建立表名為sales的表,將這個字串賦值給query
query = """CREATE TABLE sales
      (customer VARCHAR(20),product VARCHAR(40),amount FLOAT,date DATE);"""
#使用連線物件的execute()方法執行query中的SQL命令
con.execute(query)
#使用連線物件的commit()方法將修改提交(儲存)到資料庫
con.commit()
#向表中插入幾行資料
data = [('Richard Lucas','Notepad',2.50,'2019-01-02'),('Jenny Kim','Binder',4.15,'2019-01-05'),('Svetlana Crow','Printer',155.75,'2019-02-03'),('Stephen Randolph','Computer',679.40,'2019-02-20')]
#將插入語句賦給變數statement,?是佔位符
statement = "INSERT INTO sales VALUES(?,?,?)"
#因為有四個佔位符,這裡就需要提供一個包含4個值的元組,executemany()方法為data中的每個資料元組執行
#statement中的SQL命令,這裡執行了四次insert命令
con.executemany(statement,data)
#將修改儲存到資料庫
con.commit()
#查詢sales表,並將命令結果賦值給一個游標物件cursor,游標物件有execute、executemany、fetchone、
#fetchmany和fetchall方法
cursor = con.execute("SELECT * FROM sales")
#返回結果集中的所有行
rows = cursor.fetchall()
print(rows)
print('………………')
#查詢結果中行的數量
row_counter = 0
for row in rows:
  print(row)
  row_counter += 1
print('………………')
print('Number of rows: %d' % (row_counter))

Spyder右下角打印出來的結果:

[('Richard Lucas',2.5,679.4,'2019-02-20')]
………………
('Richard Lucas','2019-01-02')
('Jenny Kim','2019-01-05')
('Svetlana Crow','2019-02-03')
('Stephen Randolph','2019-02-20')
………………
Number of rows: 4

2、python內建的sqlite3模組,向表中插入新紀錄

名稱為“CSV測試資料.csv”的資料來源:

Python使用sqlite3模組內建資料庫

將本地“CSV測試資料.csv”的資料匯入到本地資料庫football_game.db中:

#!/usr/bin/env python3
#建立SQLite3記憶體資料庫,並建立帶有四個屬性的sales表
#sqlite3模組,提供了一個輕量級的基於磁碟的資料庫,不需要獨立的伺服器程序
import sqlite3
import csv
input_file = "F://python入門//資料1//CSV測試資料.csv"
#為一個簡單的本地資料庫football_game.db建立連線,football_game.db為資料庫名稱
con = sqlite3.connect('football_game.db')
#建立了一個游標
c = con.cursor()
#如果表名存在,則刪除它
drop_table = """DROP TABLE IF EXISTS football_game;"""
c.execute(drop_table)
con.commit()
#建立表名為football_game的表,將這個字串賦值給create_table
create_table = """CREATE TABLE IF NOT EXISTS football_game
      (name VARCHAR(20),sex VARCHAR(10),age INT,score INT,device_number VARCHAR(20),cost VARCHAR(20));"""
#使用連線物件的execute()方法執行create_table中的SQL命令
c.execute(create_table)
#使用連線物件的commit()方法將修改提交(儲存)到資料庫
con.commit()
#從CSV格式的輸入檔案中讀取要載入到資料庫中的資料,建立file_reader物件,用於儲存CSV中的資料集
file_reader = csv.reader(open(input_file,'r'),delimiter=',')
#從輸入檔案中讀入第一行
header = next(file_reader,None)
#將輸入的所有資料進行迴圈,先是每行迴圈,再是每列迴圈
for row in file_reader:
  data = []
  for column_index in range(len(header)):
    data.append(row[column_index])
  print(data)
  c.execute("INSERT INTO football_game VALUES(?,?)",data)
#將修改儲存到資料庫
con.commit()
print('………………')
#執行選擇所有資料的SQL
output = c.execute("SELECT * FROM football_game")
#返回結果集中的所有行,返回的是一個大的列表
rows = output.fetchall()
print(rows)
print('………………')
for row in rows:
  output = []
  for column_index in range(len(row)):
    output.append(str(row[column_index]))
  print(output)

Spyder右下角打印出來的結果:

['李剛','男','32','567','18512349553','$500.00 ']
['王紅','女','54','423','18256785181','$750.00 ']
['孫曉','25','457','13698762112','$250.00 ']
['郭亮','65','350','18654320816','$125.00 ']
['高英','15','390','18511113141','$815.00 ']
………………
[('李剛',32,567,'$500.00 '),('王紅',54,423,'$750.00 '),('孫曉',25,457,'$250.00 '),('郭亮',65,350,'$125.00 '),('高英',15,390,'$815.00 ')]
………………
['李剛','$815.00 ']

3、python內建的sqlite3模組,更新資料表中的記錄

名稱為“CSV測試資料.csv”的資料來源:

Python使用sqlite3模組內建資料庫

更新表中的記錄:

#!/usr/bin/env python3
#建立SQLite3記憶體資料庫,並建立帶有四個屬性的sales表
#sqlite3模組,提供了一個輕量級的基於磁碟的資料庫,不需要獨立的伺服器程序
import sqlite3
import csv
input_file = "F://python入門//資料1//CSV測試資料.csv"
#使用‘:memory:'在記憶體中建立了一個數據庫,建立了連線物件con來代表資料庫
con = sqlite3.connect(':memory:')
#建立表名為sales的表,將這個字串賦值給query
query = """CREATE TABLE IF NOT EXISTS sales
      (customer VARCHAR(20),'2019-02-20')]
#for tuple in data:
#  print(tuple)
#將插入語句賦給變數statement,?是佔位符
statement = "INSERT INTO sales VALUES(?,data)
#將修改儲存到資料庫
con.commit()
#讀取CSV檔案並更新特定的行
file_reader = csv.reader(open(input_file,None)
#將輸入的所有資料進行迴圈,先是每行迴圈,再是每列迴圈
for row in file_reader:
  data = []
  for column_index in range(len(header)):
    data.append(row[column_index])
  con.execute("UPDATE sales SET amount=?,date=? where customer=?;",data) 
#將修改儲存到資料庫
con.commit()
#查詢sales表,並將命令結果賦值給一個游標物件cursor,游標物件有execute、executemany、fetchone、
#fetchmany和fetchall方法
cursor = con.execute("SELECT * FROM sales")
#返回結果集中的所有行
rows = cursor.fetchall()
print(rows)
print('………………')
for row in rows:
  output = []
  for column_index in range(len(row)):
    output.append(str(row[column_index]))
  print(output)

Spyder右下角打印出來的結果:

[('Richard Lucas',4.25,'2019-11-05'),6.75,'2019-12-05'),'2019-02-20')]
………………
['Richard Lucas','4.25','2019-11-05']
['Jenny Kim','6.75','2019-12-05']
['Svetlana Crow','155.75','2019-02-03']
['Stephen Randolph','679.4','2019-02-20']

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。