使用SQLite

SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中。
Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。

一些概念

  • 是数据库中存放关系数据的集合,一个数据库里面通常都包含多个表,表和表之间通过外键关联。
  • 要操作关系数据库,首先需要连接到数据库,一个数据库连接称为 Connection。
  • 连接到数据库后,需要打开游标,称之为 Cursor,通过Cursor执行SQL语句,然后,获得执行结果。

示例

创建与插入

  1. # 导入SQLite驱动:
  2. >>> import sqlite3
  3. # 连接到SQLite数据库
  4. # 数据库文件是test.db
  5. # 如果文件不存在,会自动在当前目录创建:
  6. >>> conn = sqlite3.connect('test.db')
  7. # 创建一个Cursor:
  8. >>> cursor = conn.cursor()
  9. # 执行一条SQL语句,创建user表:
  10. >>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
  11. <sqlite3.Cursor object at 0x10f8aa260>
  12. # 继续执行一条SQL语句,插入一条记录:
  13. >>> cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')
  14. <sqlite3.Cursor object at 0x10f8aa260>
  15. # 通过rowcount获得插入的行数:
  16. >>> cursor.rowcount
  17. 1
  18. # 关闭Cursor:
  19. >>> cursor.close()
  20. # 提交事务:
  21. >>> conn.commit()
  22. # 关闭Connection:
  23. >>> conn.close()

查询

>>> conn = sqlite3.connect('test.db')
>>> cursor = conn.cursor()
# 执行查询语句:
>>> cursor.execute('select * from user where id=?', ('1',))
<sqlite3.Cursor object at 0x10f8aa340>
# 获得查询结果集:
>>> values = cursor.fetchall()
>>> values
[('1', 'Michael')]
>>> cursor.close()
>>> conn.close()

注意

  • Connection和Cursor对象,打开后一定要记得关闭
  • 使用Cursor对象执行insert,update,delete语句时,执行结果由rowcount返回影响的行数,就可以拿到执行结果。
  • 使用Cursor对象执行select语句时,通过fetchall()可以拿到结果集。结果集是一个list,每个元素都是一个tuple,对应一行记录。
  • 如果SQL语句带有参数,那么需要把参数按照位置传递给execute()方法,有几个?占位符就必须对应几个参数,例如:
    cursor.execute('select * from user where name=? and pwd=?', ('abc', 'password'))
    

使用MySQL

示例

如何连接到MySQL服务器的test数据库:

# 导入MySQL驱动:
>>> import mysql.connector
# 注意把password设为你的root口令:
>>> conn = mysql.connector.connect(user='root', password='password', database='test')
>>> cursor = conn.cursor()
# 创建user表:
>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# 插入一行记录,注意MySQL的占位符是%s:
>>> cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael'])
>>> cursor.rowcount
1
# 提交事务:
>>> conn.commit()
>>> cursor.close()
# 运行查询:
>>> cursor = conn.cursor()
>>> cursor.execute('select * from user where id = %s', ('1',))
>>> values = cursor.fetchall()
>>> values
[('1', 'Michael')]
# 关闭Cursor和Connection:
>>> cursor.close()
True
>>> conn.close()