Python学习—17 访问数据库
Python里对数据库的操作API都很统一。
SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。
Python内置了sqlite3。
输出:
[(1, 'yjc'), (2, 'yjc')]
我们发现Python里封装的数据库操作很简单:
1、获取连接conn
;
2、获取游标cursor
;
3、使用cursor.execute()
执行SQL语句;
4、使用cursor.rowcount
返回执行insert,update,delete语句受影响的行数;
5、使用cursor.fetchall()
获取查询的结果集。结果集是一个list,每个元素都是一个tuple,对应一行记录;
6、关闭游标和连接。
为了能在出错的情况下也关闭掉Connection
对象和Cursor
对象,建议实际项目里使用try:...except:...finally:...
结构。
MySQL
MySQL是最流行的关系数据库。
SQLite的特点是轻量级、可嵌入,但不能承受高并发访问,适合桌面和移动应用。而MySQL是为服务器端设计的数据库,能承受高并发访问,同时占用的内存也远远大于SQLite。
使用需要先安装MySQL:https://dev.mysql.com/downloads/mysql/
Windows版本安装时注意选择UTF-8
编码,以便正确地处理中文。
[client]
default-character-set = utf8
[mysqld]
character-set-server = utf8
collation-server = utf8_general_ci
Python并未内置MySQL的驱动。需要先安装:
Python使用MySQL示例:
# coding: utf-8
import mysql.connector
conn = mysql.connector.connect(user='root', password='123456', database='test')
cursor = conn.cursor()
cursor.execute("insert into user(id,name,age)values(null,'python', 20)")
print(cursor.rowcount)
conn.commit()
cursor.execute("select * from user order by id desc limit 3")
print(cursor.fetchall())
cursor.close()
输出:
如果SQL语句带有参数,那么需要把参数按照位置传递给cursor.execute()
方法,MySQL的占位符是,示例:
cursor.execute('select * from user where name=%s and age=%s', ['python', 20])
由于Python的DB-API定义都是通用的,所以,操作MySQL的数据库代码和SQLite类似。