Python里对数据库的操作API都很统一。

    SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。

    Python内置了sqlite3。

    输出:

    1. [(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编码,以便正确地处理中文。

    1. [client]
    2. default-character-set = utf8
    3. [mysqld]
    4. character-set-server = utf8
    5. collation-server = utf8_general_ci

    Python并未内置MySQL的驱动。需要先安装:

    Python使用MySQL示例:

    1. # coding: utf-8
    2. import mysql.connector
    3. conn = mysql.connector.connect(user='root', password='123456', database='test')
    4. cursor = conn.cursor()
    5. cursor.execute("insert into user(id,name,age)values(null,'python', 20)")
    6. print(cursor.rowcount)
    7. conn.commit()
    8. cursor.execute("select * from user order by id desc limit 3")
    9. print(cursor.fetchall())
    10. cursor.close()

    输出:

    如果SQL语句带有参数,那么需要把参数按照位置传递给cursor.execute()方法,MySQL的占位符是,示例:

    1. cursor.execute('select * from user where name=%s and age=%s', ['python', 20])

    由于Python的DB-API定义都是通用的,所以,操作MySQL的数据库代码和SQLite类似。