返回首页 《从零开始学 Python》(第二版)

预备

基本数据类型

语句和文件

函数

错误和异常

模块

保存数据

实战

用Tornado做网站

科学计算

结尾

mysql 数据库 (1)

尽管用文件形式将数据保存到磁盘,已经是一种不错的方式。但是,人们还是发明了更具有格式化特点,并且写入和读取更快速便捷的东西——数据库(如果阅读港台的资料,它们称之为“资料库”)。维基百科对数据库有比较详细的说明:

数据库指的是以一定方式储存在一起、能为多个用户共享、具有尽可能小的冗余度、与应用程序彼此独立的数据集合。

到目前为止,地球上有三种类型的数据:

  • 关系型数据库:MySQL、Microsoft Access、SQL Server、Oracle、...
  • 非关系型数据库:MongoDB、BigTable(Google)、...
  • 键值数据库:Apache Cassandra(Facebook)、LevelDB(Google) ...

在本教程中,我们主要介绍常用的开源的数据库,其中 MySQL 是典型代表。

概况

MySQL 是一个使用非常广泛的数据库,很多网站都是用它。关于这个数据库有很多传说。例如维基百科上这么说:

MySQL(官方发音为英语发音:/maɪ ˌɛskjuːˈɛl/ "My S-Q-L",[1],但也经常读作英语发音:/maɪ ˈsiːkwəl/ "My Sequel")原本是一个开放源代码的关系数据库管理系统,原开发者为瑞典的 MySQL AB 公司,该公司于 2008 年被升阳微系统(Sun Microsystems)收购。2009 年,甲骨文公司(Oracle)收购升阳微系统公司,MySQL 成为 Oracle 旗下产品。

MySQL 在过去由于性能高、成本低、可靠性好,已经成为最流行的开源数据库,因此被广泛地应用在 Internet 上的中小型网站中。随着 MySQL 的不断成熟,它也逐渐用于更多大规模网站和应用,比如维基百科、Google 和 Facebook 等网站。非常流行的开源软件组合 LAMP 中的“M”指的就是 MySQL。

但被甲骨文公司收购后,Oracle 大幅调涨 MySQL 商业版的售价,且甲骨文公司不再支持另一个自由软件项目 OpenSolaris 的发展,因此导致自由软件社区们对于 Oracle 是否还会持续支持 MySQL 社区版(MySQL 之中唯一的免费版本)有所隐忧,因此原先一些使用 MySQL 的开源软件逐渐转向其它的数据库。例如维基百科已于 2013 年正式宣布将从 MySQL 迁移到 MariaDB 数据库。

不管怎么着,MySQL 依然是一个不错的数据库选择,足够支持读者完成一个相当不小的网站。

安装

你的电脑或许不会天生就有 MySQL(是不是有的操作系统,在安装的时候就内置了呢?的确有,所以特别推荐 Linux 的某发行版),它本质上也是一个程序,若有必要,须安装。

我用 ubuntu 操作系统演示,因为我相信读者将来在真正的工程项目中,多数情况下是要操作 Linux 系统的服务器,并且,我酷爱用 ubuntu。还有,本教程的目标是 from beginner to master,不管是不是真的 master,总要装得像,Linux 能够给你撑门面。

第一步,在 shell 端运行如下命令:

sudo apt-get install mysql-server

运行完毕,就安装好了这个数据库。是不是很简单呢?当然,当然,还要进行配置。

第二步,配置 MySQL

安装之后,运行:

service mysqld start

启动 mysql 数据库。然后进行下面的操作,对其进行配置。

默认的 MySQL 安装之后根用户是没有密码的,注意,这里有一个名词“根用户”,其用户名是:root。运行:

$mysql -u root

在这里之所以用 -u root 是因为我现在是一般用户(firehare),如果不加 -u root 的话,mysql 会以为是 firehare 在登录。

进入 mysql 之后,会看到>符号开头,这就是 mysql 的命令操作界面了。

下面设置 Mysql 中的 root 用户密码了,否则,Mysql 服务无安全可言了。

mysql> GRANT ALL PRIVILEGES ON *.* TO root@localhost IDENTIFIED BY "123456";

用 123456 做为 root 用户的密码,应该是非常愚蠢的,如果在真正的项目中,最好别这样做,要用大小写字母与数字混合的密码,且不少于 8 位。

以后如果在登录数据库,就可以用刚才设置的密码了。

运行

安装之后,就要运行它,并操作这个数据库。

$ mysql -u root -p
Enter password: 

输入数据库的密码,之后出现:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 373
Server version: 5.5.38-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

看到这个界面内容,就说明你已经进入到数据里面了。接下来就可以对这个数据进行操作。例如:

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| carstore           |
| cutvideo           |
| itdiffer           |
| mysql              |
| performance_schema |
| test               |
+--------------------+

用这个命令,就列出了当前已经有的数据库。

对数据库的操作,除了用命令之外,还可以使用一些可视化工具。比如 phpmyadmin 就是不错的。

更多数据库操作的知识,这里就不介绍了,读者可以参考有关书籍。

MySQL 数据库已经安装好,但是 Python 还不能操作它,还要继续安装 Python 操作数据库的模块——Python-MySQLdb

安装 Python-MySQLdb

Python-MySQLdb 是一个接口程序,Python 通过它对 mysql 数据实现各种操作。

在编程中,会遇到很多类似的接口程序,通过接口程序对另外一个对象进行操作。接口程序就好比钥匙,如果要开锁,人直接用手指去捅,肯定是不行的,那么必须借助工具,插入到锁孔中,把锁打开,之后,门开了,就可以操作门里面的东西了。那么打开锁的工具就是接口程序。谁都知道,用对应的钥匙开锁是最好的,如果用别的工具(比如锤子),或许不便利(其实还分人,也就是人开锁的水平,如果是江洋大盗或者小毛贼什么的,擅长开锁,用别的工具也便利了),也就是接口程序不同,编码水平不同,都是考虑因素。

啰嗦这么多,一言蔽之,Python-MySQLdb 就是打开 MySQL 数据库的钥匙。

如果要源码安装,可以这里下载 Python-mysqldb:https://pypi.Python.org/pypi/MySQL-Python/

下载之后就可以安装了。

ubuntu 下可以这么做:

sudo apt-get install build-essential Python-dev libmysqlclient-dev
sudo apt-get install Python-MySQLdb

也可以用 pip 来安装:

pip install mysql-Python

安装之后,在 python 交互模式下:

>>> import MySQLdb 

如果不报错,恭喜你,已经安装好了。如果报错,恭喜你,可以借着错误信息提高自己的计算机水平了,请求助于 google 大神。

连接数据库

要先找到老婆,才能谈如何养育自己的孩子,同理连接数据库之先要建立数据库。

$ mysql -u root -p
Enter password:                             

进入到数据库操作界面:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 373
Server version: 5.5.38-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

输入如下命令,建立一个数据库:

mysql> create database qiwsirtest character set utf8;
Query OK, 1 row affected (0.00 sec)

注意上面的指令,如果仅仅输入:create database qiwsirtest,也可以,但是,我在后面增加了 character set utf8,意思是所建立的数据库 qiwsirtest,编码是 utf-8 的,这样存入汉字就不是乱码了。

看到那一行提示:Query OK, 1 row affected (0.00 sec),就说明这个数据库已经建立好了,名字叫做:qiwsirtest

数据库建立之后,就可以用 Python 通过已经安装的 mysqldb 来连接这个名字叫做 qiwsirtest 的库了。

>>> import MySQLdb
>>> conn = MySQLdb.connect(host="localhost",user="root",passwd="123123",db="qiwsirtest",port=3306,charset="utf8")

逐个解释上述命令的含义:

  • host:等号的后面应该填写 mysql 数据库的地址,因为就数据库就在本机上(也称作本地),所以使用 localhost,注意引号。如果在其它的服务器上,这里应该填写 ip 地址。一般中小型的网站,数据库和程序都是在同一台服务器(计算机)上,就使用 localhost 了。
  • user:登录数据库的用户名,这里一般填写"root",还是要注意引号。当然,如果读者命名了别的用户名,数据库管理者提供了专有用户名,就更改为相应用户。但是,不同用户的权限可能不同,所以,在程序中,如果要操作数据库,还要注意所拥有的权限。在这里用 root,就放心了,什么权限都有啦。不过,这样做,在大型系统中是应该避免的。
  • passwd:上述 user 账户对应的登录 mysql 的密码。我在上面的例子中用的密码是"123123"。不要忘记引号。
  • db:就是刚刚通 create 命令建立的数据库,我建立的数据库名字是"qiwsirtest",还是要注意引号。看官如果建立的数据库名字不是这个,就写自己所建数据库名字。
  • port:一般情况,mysql 的默认端口是 3306,当 mysql 被安装到服务器之后,为了能够允许网络访问,服务器(计算机)要提供一个访问端口给它。
  • charset:这个设置,在很多教程中都不写,结果在真正进行数据存储的时候,发现有乱码。这里我将 qiwsirtest 这个数据库的编码设置为 utf-8 格式,这样就允许存入汉字而无乱码了。注意,在 mysql 设置中,utf-8 写成 utf8,没有中间的横线。但是在 Python 文件开头和其它地方设置编码格式的时候,要写成 utf-8。切记!

注:connect 中的 host、user、passwd 等可以不写,只有在写的时候按照 host、user、passwd、db (可以不写)、port 顺序写就可以,端口号 port=3306 还是不要省略的为好,如果没有 db 在 port 前面,直接写 3306 会报错.

其实,关于 connect 的参数还不少,下面摘抄来自mysqldb 官方文档的内容,把所有的参数都列出来,还有相关说明,请看官认真阅读。不过,上面几个是常用的,其它的看情况使用。

connect(parameters...)

Constructor for creating a connection to the database. Returns a Connection Object. Parameters are the same as for the MySQL C API. In addition, there are a few additional keywords that correspond to what you would pass mysql_options() before connecting. Note that some parameters must be specified as keyword arguments! The default value for each parameter is NULL or zero, as appropriate. Consult the MySQL documentation for more details. The important parameters are:

  • host: name of host to connect to. Default: use the local host via a UNIX socket (where applicable)
  • user: user to authenticate as. Default: current effective user.
  • passwd: password to authenticate with. Default: no password.
  • db: database to use. Default: no default database.
  • port: TCP port of MySQL server. Default: standard port (3306).
  • unix_socket: location of UNIX socket. Default: use default location or TCP for remote hosts.
  • conv: type conversion dictionary. Default: a copy of MySQLdb.converters.conversions
  • compress: Enable protocol compression. Default: no compression.
  • connect_timeout: Abort if connect is not completed within given number of seconds. Default: no timeout (?)
  • named_pipe: Use a named pipe (Windows). Default: don't.
  • init_command: Initial command to issue to server upon connection. Default: Nothing.
  • read_default_file: MySQL configuration file to read; see the MySQL documentation for mysql_options().
  • read_default_group: Default group to read; see the MySQL documentation for mysql_options().
  • cursorclass: cursor class that cursor() uses, unless overridden. Default: MySQLdb.cursors.Cursor. This must be a keyword parameter.
  • use_unicode: If True, CHAR and VARCHAR and TEXT columns are returned as Unicode strings, using the configured character set. It is best to set the default encoding in the server configuration, or client configuration (read with read_default_file). If you change the character set after connecting (MySQL-4.1 and later), you'll need to put the correct character set name in connection.charset.

If False, text-like columns are returned as normal strings, but you can always write Unicode strings.

This must be a keyword parameter.

  • charset: If present, the connection character set will be changed to this character set, if they are not equal. Support for changing the character set requires MySQL-4.1 and later server; if the server is too old, UnsupportedError will be raised. This option implies use_unicode=True, but you can override this with use_unicode=False, though you probably shouldn't.

If not present, the default character set is used.

This must be a keyword parameter.

  • sql_mode: If present, the session SQL mode will be set to the given string. For more information on sql_mode, see the MySQL documentation. Only available for 4.1 and newer servers.

If not present, the session SQL mode will be unchanged.

This must be a keyword parameter.

  • ssl: This parameter takes a dictionary or mapping, where the keys are parameter names used by the mysql_ssl_set MySQL C API call. If this is set, it initiates an SSL connection to the server; if there is no SSL support in the client, an exception is raised. This must be a keyword parameter.

已经完成了数据库的连接。


总目录   |   上节:将数据存入文件   |   下节:mysql数据库(2)

如果你认为有必要打赏我,请通过支付宝:qiwsir@126.com,不胜感激。