当前位置:Gxlcms > 数据库问题 > python内置的sqlite3模块,使用其内置数据库

python内置的sqlite3模块,使用其内置数据库

时间:2021-07-01 10:21:17 帮助过:31人阅读

!/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模块,向表中插入新纪录

 

python内置的sqlite3模块,使用其内置数据库

标签:变量   step   sele   方法   inter   arch   nbsp   对象   number   

人气教程排行