python sqlite3的使用

1.sqlite3的安装

python2.5 以上版本 默认自带sqlite3模块
python3.6 以上版本 默认自带sqlite3模块

2.链接sqlite3数据库

```
# 导入sqlite3模块
import sqlite3

# 创建链接对象
# 打开一个到 SQLite 数据库文件 db.sqlite3 的链接
# 如果该数据库不存在则会自动创建,可以指定带有文件路径的文件名
conn = sqlite3.connect('db.sqlite3')
```

3.获取游标对象

```
# 获取游标对象用来操作数据库
cursor = conn.cursor()
```

4.操作sqlite数据库

* 创建表
    ```
    # 插入user表
    # id int型 主键自增
    # name varchar型 最大长度20 不能为空
    cursor.execute('''create table user(id integer primary key autoincrement,name varchar(20) not null)''')
    ```
* 插入记录
    ```
    # 插入一条id=1 name='xiaoqiang'的记录
    cursor.execute('''insert into user(id,name) values(1,'xiaoqiang')''')
    ```
* 查找记录
    ```
    # 查找user表中id=1的记录
    cursor.execute('''select * from user where id=1''')
    # 获得结果
    values = cursor.fetchall()
    values
    [(u'1', u'Michael')]
    ```
* 删除记录
    ```
    # 删除id=1的记录
    sursor.excute('''delete from user where id=1''')
    ```
* 修改记录
    ```
    # 修改id=1记录中的name为xiaoming
    sursor.excute('''update user set name='xiaoming' where id=1''')
    ```

5.提交事务关闭数据库

前面的修改只是将数据缓存在内存中并没有正真的写入数据库,需要提交事务才能将数据写入数据库
操作完后要确保打开的Connection对象和Cursor对象都正确地被关闭,否则,资源就会泄露。
```
# 修改id=1记录中的name为xiaoming
sursor.excute('''update user set name='xiaoming' where id=1''')
# 提交事务
conn.commit()
# 关闭链接
conn.close()
```

 

 

  • 1
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值