鍍金池/ 教程/ Python/ mysql 數(shù)據(jù)庫 (1)
標(biāo)準(zhǔn)庫 (4)
如何成為 Python 高手
標(biāo)準(zhǔn)庫 (6)
標(biāo)準(zhǔn)庫 (3)
類(2)
Pandas 使用 (2)
xml
用 tornado 做網(wǎng)站 (5)
文件(1)
練習(xí)
列表(3)
從小工到專家
除法
錯(cuò)誤和異常 (2)
函數(shù)(1)
用 tornado 做網(wǎng)站 (7)
為做網(wǎng)站而準(zhǔn)備
函數(shù)練習(xí)
標(biāo)準(zhǔn)庫 (8)
Pandas 使用 (1)
回顧 list 和 str
字典(1)
用 tornado 做網(wǎng)站 (3)
字符串(1)
函數(shù)(2)
寫一個(gè)簡單的程序
將數(shù)據(jù)存入文件
語句(5)
SQLite 數(shù)據(jù)庫
集成開發(fā)環(huán)境(IDE)
集合(1)
類(1)
用 tornado 做網(wǎng)站 (6)
用 tornado 做網(wǎng)站 (2)
自省
語句(4)
錯(cuò)誤和異常 (1)
用 tornado 做網(wǎng)站 (4)
集合(2)
列表(1)
標(biāo)準(zhǔn)庫 (1)
生成器
mysql 數(shù)據(jù)庫 (1)
第三方庫
實(shí)戰(zhàn)
運(yùn)算符
類(3)
字典(2)
語句(1)
數(shù)和四則運(yùn)算
語句(2)
文件(2)
MySQL 數(shù)據(jù)庫 (2)
電子表格
迭代器
mongodb 數(shù)據(jù)庫 (1)
特殊方法 (2)
特殊方法 (1)
字符編碼
編寫模塊
用 tornado 做網(wǎng)站 (1)
標(biāo)準(zhǔn)庫 (5)
函數(shù)(4)
類(5)
字符串(2)
關(guān)于 Python 的故事
函數(shù)(3)
字符串(4)
處理股票數(shù)據(jù)
常用數(shù)學(xué)函數(shù)和運(yùn)算優(yōu)先級(jí)
字符串(3)
為計(jì)算做準(zhǔn)備
多態(tài)和封裝
類(4)
迭代
語句(3)
錯(cuò)誤和異常 (3)
分析 Hello
Python 安裝
標(biāo)準(zhǔn)庫 (2)
列表(2)
元組

mysql 數(shù)據(jù)庫 (1)

盡管用文件形式將數(shù)據(jù)保存到磁盤,已經(jīng)是一種不錯(cuò)的方式。但是,人們還是發(fā)明了更具有格式化特點(diǎn),并且寫入和讀取更快速便捷的東西——數(shù)據(jù)庫(如果閱讀港臺(tái)的資料,它們稱之為“資料庫”)。維基百科對(duì)數(shù)據(jù)庫有比較詳細(xì)的說明:

數(shù)據(jù)庫指的是以一定方式儲(chǔ)存在一起、能為多個(gè)用戶共享、具有盡可能小的冗余度、與應(yīng)用程序彼此獨(dú)立的數(shù)據(jù)集合。

到目前為止,地球上有三種類型的數(shù)據(jù):

  • 關(guān)系型數(shù)據(jù)庫:MySQL、Microsoft Access、SQL Server、Oracle、...
  • 非關(guān)系型數(shù)據(jù)庫:MongoDB、BigTable(Google)、...
  • 鍵值數(shù)據(jù)庫:Apache Cassandra(Facebook)、LevelDB(Google) ...

在本教程中,我們主要介紹常用的開源的數(shù)據(jù)庫,其中 MySQL 是典型代表。

概況

MySQL 是一個(gè)使用非常廣泛的數(shù)據(jù)庫,很多網(wǎng)站都是用它。關(guān)于這個(gè)數(shù)據(jù)庫有很多傳說。例如維基百科上這么說:

MySQL(官方發(fā)音為英語發(fā)音:/ma? ??skju???l/ "My S-Q-L",[1],但也經(jīng)常讀作英語發(fā)音:/ma? ?si?kw?l/ "My Sequel")原本是一個(gè)開放源代碼的關(guān)系數(shù)據(jù)庫管理系統(tǒng),原開發(fā)者為瑞典的 MySQL AB 公司,該公司于 2008 年被升陽微系統(tǒng)(Sun Microsystems)收購。2009 年,甲骨文公司(Oracle)收購升陽微系統(tǒng)公司,MySQL 成為 Oracle 旗下產(chǎn)品。

MySQL 在過去由于性能高、成本低、可靠性好,已經(jīng)成為最流行的開源數(shù)據(jù)庫,因此被廣泛地應(yīng)用在 Internet 上的中小型網(wǎng)站中。隨著 MySQL 的不斷成熟,它也逐漸用于更多大規(guī)模網(wǎng)站和應(yīng)用,比如維基百科、Google 和 Facebook 等網(wǎng)站。非常流行的開源軟件組合 LAMP 中的“M”指的就是 MySQL。

但被甲骨文公司收購后,Oracle 大幅調(diào)漲 MySQL 商業(yè)版的售價(jià),且甲骨文公司不再支持另一個(gè)自由軟件項(xiàng)目 OpenSolaris 的發(fā)展,因此導(dǎo)致自由軟件社區(qū)們對(duì)于 Oracle 是否還會(huì)持續(xù)支持 MySQL 社區(qū)版(MySQL 之中唯一的免費(fèi)版本)有所隱憂,因此原先一些使用 MySQL 的開源軟件逐漸轉(zhuǎn)向其它的數(shù)據(jù)庫。例如維基百科已于 2013 年正式宣布將從 MySQL 遷移到 MariaDB 數(shù)據(jù)庫。

不管怎么著,MySQL 依然是一個(gè)不錯(cuò)的數(shù)據(jù)庫選擇,足夠支持讀者完成一個(gè)相當(dāng)不小的網(wǎng)站。

安裝

你的電腦或許不會(huì)天生就有 MySQL(是不是有的操作系統(tǒng),在安裝的時(shí)候就內(nèi)置了呢?的確有,所以特別推薦 Linux 的某發(fā)行版),它本質(zhì)上也是一個(gè)程序,若有必要,須安裝。

我用 ubuntu 操作系統(tǒng)演示,因?yàn)槲蚁嘈抛x者將來在真正的工程項(xiàng)目中,多數(shù)情況下是要操作 Linux 系統(tǒng)的服務(wù)器,并且,我酷愛用 ubuntu。還有,本教程的目標(biāo)是 from beginner to master,不管是不是真的 master,總要裝得像,Linux 能夠給你撐門面。

第一步,在 shell 端運(yùn)行如下命令:

sudo apt-get install mysql-server

運(yùn)行完畢,就安裝好了這個(gè)數(shù)據(jù)庫。是不是很簡單呢?當(dāng)然,當(dāng)然,還要進(jìn)行配置。

第二步,配置 MySQL

安裝之后,運(yùn)行:

service mysqld start

啟動(dòng) mysql 數(shù)據(jù)庫。然后進(jìn)行下面的操作,對(duì)其進(jìn)行配置。

默認(rèn)的 MySQL 安裝之后根用戶是沒有密碼的,注意,這里有一個(gè)名詞“根用戶”,其用戶名是:root。運(yùn)行:

$mysql -u root

在這里之所以用 -u root 是因?yàn)槲椰F(xiàn)在是一般用戶(firehare),如果不加 -u root 的話,mysql 會(huì)以為是 firehare 在登錄。

進(jìn)入 mysql 之后,會(huì)看到>符號(hào)開頭,這就是 mysql 的命令操作界面了。

下面設(shè)置 Mysql 中的 root 用戶密碼了,否則,Mysql 服務(wù)無安全可言了。

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

用 123456 做為 root 用戶的密碼,應(yīng)該是非常愚蠢的,如果在真正的項(xiàng)目中,最好別這樣做,要用大小寫字母與數(shù)字混合的密碼,且不少于 8 位。

以后如果在登錄數(shù)據(jù)庫,就可以用剛才設(shè)置的密碼了。

運(yùn)行

安裝之后,就要運(yùn)行它,并操作這個(gè)數(shù)據(jù)庫。

$ mysql -u root -p
Enter password: 

輸入數(shù)據(jù)庫的密碼,之后出現(xiàn):

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> 

看到這個(gè)界面內(nèi)容,就說明你已經(jīng)進(jìn)入到數(shù)據(jù)里面了。接下來就可以對(duì)這個(gè)數(shù)據(jù)進(jìn)行操作。例如:

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

用這個(gè)命令,就列出了當(dāng)前已經(jīng)有的數(shù)據(jù)庫。

對(duì)數(shù)據(jù)庫的操作,除了用命令之外,還可以使用一些可視化工具。比如 phpmyadmin 就是不錯(cuò)的。

更多數(shù)據(jù)庫操作的知識(shí),這里就不介紹了,讀者可以參考有關(guān)書籍。

MySQL 數(shù)據(jù)庫已經(jīng)安裝好,但是 Python 還不能操作它,還要繼續(xù)安裝 Python 操作數(shù)據(jù)庫的模塊——Python-MySQLdb

安裝 Python-MySQLdb

Python-MySQLdb 是一個(gè)接口程序,Python 通過它對(duì) mysql 數(shù)據(jù)實(shí)現(xiàn)各種操作。

在編程中,會(huì)遇到很多類似的接口程序,通過接口程序?qū)α硗庖粋€(gè)對(duì)象進(jìn)行操作。接口程序就好比鑰匙,如果要開鎖,人直接用手指去捅,肯定是不行的,那么必須借助工具,插入到鎖孔中,把鎖打開,之后,門開了,就可以操作門里面的東西了。那么打開鎖的工具就是接口程序。誰都知道,用對(duì)應(yīng)的鑰匙開鎖是最好的,如果用別的工具(比如錘子),或許不便利(其實(shí)還分人,也就是人開鎖的水平,如果是江洋大盜或者小毛賊什么的,擅長開鎖,用別的工具也便利了),也就是接口程序不同,編碼水平不同,都是考慮因素。

啰嗦這么多,一言蔽之,Python-MySQLdb 就是打開 MySQL 數(shù)據(jù)庫的鑰匙。

如果要源碼安裝,可以這里下載 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 

如果不報(bào)錯(cuò),恭喜你,已經(jīng)安裝好了。如果報(bào)錯(cuò),恭喜你,可以借著錯(cuò)誤信息提高自己的計(jì)算機(jī)水平了,請求助于 google 大神。

連接數(shù)據(jù)庫

要先找到老婆,才能談如何養(yǎng)育自己的孩子,同理連接數(shù)據(jù)庫之先要建立數(shù)據(jù)庫。

$ mysql -u root -p
Enter password:                             

進(jìn)入到數(shù)據(jù)庫操作界面:

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> 

輸入如下命令,建立一個(gè)數(shù)據(jù)庫:

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

注意上面的指令,如果僅僅輸入:create database qiwsirtest,也可以,但是,我在后面增加了 character set utf8,意思是所建立的數(shù)據(jù)庫 qiwsirtest,編碼是 utf-8 的,這樣存入漢字就不是亂碼了。

看到那一行提示:Query OK, 1 row affected (0.00 sec),就說明這個(gè)數(shù)據(jù)庫已經(jīng)建立好了,名字叫做:qiwsirtest

數(shù)據(jù)庫建立之后,就可以用 Python 通過已經(jīng)安裝的 mysqldb 來連接這個(gè)名字叫做 qiwsirtest 的庫了。

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

逐個(gè)解釋上述命令的含義:

  • host:等號(hào)的后面應(yīng)該填寫 mysql 數(shù)據(jù)庫的地址,因?yàn)榫蛿?shù)據(jù)庫就在本機(jī)上(也稱作本地),所以使用 localhost,注意引號(hào)。如果在其它的服務(wù)器上,這里應(yīng)該填寫 ip 地址。一般中小型的網(wǎng)站,數(shù)據(jù)庫和程序都是在同一臺(tái)服務(wù)器(計(jì)算機(jī))上,就使用 localhost 了。
  • user:登錄數(shù)據(jù)庫的用戶名,這里一般填寫"root",還是要注意引號(hào)。當(dāng)然,如果讀者命名了別的用戶名,數(shù)據(jù)庫管理者提供了專有用戶名,就更改為相應(yīng)用戶。但是,不同用戶的權(quán)限可能不同,所以,在程序中,如果要操作數(shù)據(jù)庫,還要注意所擁有的權(quán)限。在這里用 root,就放心了,什么權(quán)限都有啦。不過,這樣做,在大型系統(tǒng)中是應(yīng)該避免的。
  • passwd:上述 user 賬戶對(duì)應(yīng)的登錄 mysql 的密碼。我在上面的例子中用的密碼是"123123"。不要忘記引號(hào)。
  • db:就是剛剛通 create 命令建立的數(shù)據(jù)庫,我建立的數(shù)據(jù)庫名字是"qiwsirtest",還是要注意引號(hào)??垂偃绻⒌臄?shù)據(jù)庫名字不是這個(gè),就寫自己所建數(shù)據(jù)庫名字。
  • port:一般情況,mysql 的默認(rèn)端口是 3306,當(dāng) mysql 被安裝到服務(wù)器之后,為了能夠允許網(wǎng)絡(luò)訪問,服務(wù)器(計(jì)算機(jī))要提供一個(gè)訪問端口給它。
  • charset:這個(gè)設(shè)置,在很多教程中都不寫,結(jié)果在真正進(jìn)行數(shù)據(jù)存儲(chǔ)的時(shí)候,發(fā)現(xiàn)有亂碼。這里我將 qiwsirtest 這個(gè)數(shù)據(jù)庫的編碼設(shè)置為 utf-8 格式,這樣就允許存入漢字而無亂碼了。注意,在 mysql 設(shè)置中,utf-8 寫成 utf8,沒有中間的橫線。但是在 Python 文件開頭和其它地方設(shè)置編碼格式的時(shí)候,要寫成 utf-8。切記!

注:connect 中的 host、user、passwd 等可以不寫,只有在寫的時(shí)候按照 host、user、passwd、db (可以不寫)、port 順序?qū)懢涂梢裕丝谔?hào) port=3306 還是不要省略的為好,如果沒有 db 在 port 前面,直接寫 3306 會(huì)報(bào)錯(cuò).

其實(shí),關(guān)于 connect 的參數(shù)還不少,下面摘抄來自mysqldb 官方文檔的內(nèi)容,把所有的參數(shù)都列出來,還有相關(guān)說明,請看官認(rèn)真閱讀。不過,上面幾個(gè)是常用的,其它的看情況使用。

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.

已經(jīng)完成了數(shù)據(jù)庫的連接。


總目錄   |   上節(jié):將數(shù)據(jù)存入文件   |   下節(jié):mysql數(shù)據(jù)庫(2)

如果你認(rèn)為有必要打賞我,請通過支付寶:qiwsir@126.com,不勝感激。