Loading

Python学习--17 访问数据库

实际开发中,我们会经常用到数据库。

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

SQLite

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

Python内置了sqlite3。

#coding:utf-8
import sqlite3

conn = sqlite3.connect('test.db')
cursor = conn.cursor()

# sqlite创建表时,若id为INTEGER类型且为主键,可以自动递增,在插入数据时id填NULL即可
# cursor.execute('create table user(id integer primary key, name varchar(25))') #执行一次

# 插入一条数据
cursor.execute('insert into user(id,name)values(NULL,"yjc")')

# 返回影响的行数
print(cursor.rowcount)

#提交事务,否则上述SQL不会提交执行
conn.commit()

# 执行查询
cursor.execute('select * from user')

# 获取查询结果
print(cursor.fetchall())

# 关闭游标和连接
cursor.close()
conn.close()

输出:

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、关闭游标和连接。

如果SQL语句带有参数,那么需要把参数按照位置传递给cursor.execute()方法,有几个?占位符就必须对应几个参数,示例:

cursor.execute('select * from user where name=? ', ['abc'])

为了能在出错的情况下也关闭掉Connection对象和Cursor对象,建议实际项目里使用try:...except:...finally:...结构。

MySQL

MySQL是最流行的关系数据库。

SQLite的特点是轻量级、可嵌入,但不能承受高并发访问,适合桌面和移动应用。而MySQL是为服务器端设计的数据库,能承受高并发访问,同时占用的内存也远远大于SQLite。

使用需要先安装MySQL:https://dev.mysql.com/downloads/mysql/

Windows版本安装时注意选择UTF-8编码,以便正确地处理中文。

MySQL的配置文件是my.ini,Linux一般位于/etc/my.cnf。配置里需要设置编码为utf-8。配置示例:

[client]
default-character-set = utf8

[mysqld]
default-storage-engine = INNODB
character-set-server = utf8
collation-server = utf8_general_ci

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

$ pip3 install mysql-connector

Collecting mysql-connector
  Downloading mysql-connector-2.1.4.zip (355kB)
    100% |████████████████████████████████| 358kB 355kB/s
Building wheels for collected packages: mysql-connector
  Running setup.py bdist_wheel for mysql-connector ... done
Successfully built mysql-connector
Installing collected packages: mysql-connector
Successfully installed mysql-connector-2.1.4

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()
conn.close

输出:

1
[(25, 'python', 1, 20, 1), (24, 'python', 1, 20, 1), (23, 't2', 2, 23, 1)]

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

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

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

posted @ 2017-02-08 23:31  飞鸿影  阅读(751)  评论(0编辑  收藏  举报