Python连接.sqlite文件
# 引入sqlite3库
import sqlite3
# 连接数据库
with sqlite3.connect('G://test.sqlite') as con:
# 获得一个对象
c = con.cursor()
cursor用来执行命令的方法
execute(self, query, args)
执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
cursor用来接收返回值的方法
fetchall()
接收全部的返回结果行
fetchone(self)
返回一条结果行.
1. 创建表
创建名为test_table的TABLE,并且包含data(text类型),city(text类型),value(real类型)
c.execute('''CREATE TABLE test_table
(date text, city text, value real)''')
2. 插入
在test_table中插入date = 2017-6-25, city = bj, value=100
c.execute('''INSERT INTO test_table VALUES
('2017-6-25', 'bj', 100)''')
对应SQL语言为
insert into [table] ([column],[column],[column]) values(?,?,?);
3. 删除
在test_table中删除‘city’列中名为’bj’的数据
delete from test_table where city = 'bj';
对应SQL语言为
delete from 表名 where 列名 = ‘张益达’
4. 查
显示test_table中所有数据
c.execute('''select * from test_table ''')
print(c.fetchall())
对应SQL语言为
select * from [table] where [column] = ?
5. 改
将’data’列为’207’的数据的’city’改为’sz’
update test_table set city = 'sz' where date = '207';
对应SQL语言为
update 表名 set 列名 = 新值 where 列名 = 要修改的值