我们在你们那里的时候,曾吩咐你们说,若有人不肯作工,就不可吃饭。因我们听说,在你们中间有人不按规矩而行,什么工都不作,反倒专管闲事。我们靠主耶稣基督,吩咐、劝解这样的人,要安静作工,吃自己的饭。(2 THESSALONIANS 3:10-12)

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,不胜感激。