歡迎您光臨本站 註冊首頁

Python使用sqlite3模塊內置數據庫

←手機掃碼閱讀     f2h0b53ohn @ 2020-05-08 , reply:0

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', 'Notepad', 2.5, '2019-01-02'), ('Jenny Kim', 'Binder', 4.15, '2019-01-05'), ('Svetlana Crow', 'Printer', 155.75, '2019-02-03'), ('Stephen Randolph', 'Computer', 679.4, '2019-02-20')] ……………… ('Richard Lucas', 'Notepad', 2.5, '2019-01-02') ('Jenny Kim', 'Binder', 4.15, '2019-01-05') ('Svetlana Crow', 'Printer', 155.75, '2019-02-03') ('Stephen Randolph', 'Computer', 679.4, '2019-02-20') ……………… Number of rows: 4
2、python內置的sqlite3模塊,向表中插入新紀錄
名稱為“CSV測試數據.csv”的數據源:
將本地“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, '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', '18512349553', '$500.00 '] ['王紅', '女', '54', '423', '18256785181', '$750.00 '] ['孫曉', '女', '25', '457', '13698762112', '$250.00 '] ['郭亮', '男', '65', '350', '18654320816', '$125.00 '] ['高英', '女', '15', '390', '18511113141', '$815.00 ']
3、python內置的sqlite3模塊,更新數據表中的記錄
名稱為“CSV測試數據.csv”的數據源:
更新表中的記錄:
#!/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), 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')] #for tuple in data: # print(tuple)

 #將插入語句賦給變量statement,?是佔位符 statement = "INSERT INTO sales VALUES(?,?,?,?)" #因為有四個佔位符,這裡就需要提供一個包含4個值的元組,executemany()方法為data中的每個數據元組執行 #statement中的SQL命令,這裡執行了四次insert命令 con.executemany(statement,data) #將修改保存到數據庫 con.commit() #讀取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]) 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', 'Notepad', 4.25, '2019-11-05'), 

('Jenny Kim', 'Binder', 6.75, '2019-12-05'), 

('Svetlana Crow', 'Printer', 155.75, '2019-02-03'), 

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


[f2h0b53ohn ] Python使用sqlite3模塊內置數據庫已經有272次圍觀

http://coctec.com/docs/python/shhow-post-233285.html