盡管用文件形式將數據保存到磁盤,已經是一種不錯的方式。但是,人們還是發明了更具有格式化特點,并且寫入和讀取更快速便捷的東西——數據庫(如果閱讀港臺的資料,它們稱之為“資料庫”)。維基百科對數據庫有比較詳細的說明:
> 數據庫指的是以一定方式儲存在一起、能為多個用戶共享、具有盡可能小的冗余度、與應用程序彼此獨立的數據集合。
到目前為止,地球上有三種類型的數據:
* 關系型數據庫:MySQL、Microsoft Access、SQL Server、Oracle、...
* 非關系型數據庫:MongoDB、BigTable(Google)、...
* 鍵值數據庫:Apache Cassandra(Facebook)、LevelDB(Google) ...
在本教程中,我們主要介紹常用的開源的數據庫,其中MySQL是典型代表。
### [](https://github.com/qiwsir/StarterLearningPython/blob/master/230.md#概況)概況
MySQL是一個使用非常廣泛的數據庫,很多網站都是用它。關于這個數據庫有很多傳說。例如[維基百科上這么說:](http://zh.wikipedia.org/wiki/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依然是一個不錯的數據庫選擇,足夠支持讀者完成一個相當不小的網站。
### [](https://github.com/qiwsir/StarterLearningPython/blob/master/230.md#安裝)安裝
你的電腦或許不會天生就有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位。
以后如果在登錄數據庫,就可以用剛才設置的密碼了。
### [](https://github.com/qiwsir/StarterLearningPython/blob/master/230.md#運行)運行
安裝之后,就要運行它,并操作這個數據庫。
~~~
$ 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
### [](https://github.com/qiwsir/StarterLearningPython/blob/master/230.md#安裝python-mysqldb)安裝python-MySQLdb
python-MySQLdb是一個接口程序,python通過它對mysql數據實現各種操作。
在編程中,會遇到很多類似的接口程序,通過接口程序對另外一個對象進行操作。接口程序就好比鑰匙,如果要開鎖,人直接用手指去捅,肯定是不行的,那么必須借助工具,插入到鎖孔中,把鎖打開,之后,門開了,就可以操作門里面的東西了。那么打開鎖的工具就是接口程序。誰都知道,用對應的鑰匙開鎖是最好的,如果用別的工具(比如錘子),或許不便利(其實還分人,也就是人開鎖的水平,如果是江洋大盜或者小毛賊什么的,擅長開鎖,用別的工具也便利了),也就是接口程序不同,編碼水平不同,都是考慮因素。
啰嗦這么多,一言蔽之,python-MySQLdb就是打開MySQL數據庫的鑰匙。
如果要源碼安裝,可以這里下載python-mysqldb:[https://pypi.python.org/pypi/MySQL-python/](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大神。
### [](https://github.com/qiwsir/StarterLearningPython/blob/master/230.md#連接數據庫)連接數據庫
要先找到老婆,才能談如何養育自己的孩子,同理連接數據庫之先要建立數據庫。
~~~
$ 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官方文檔的內容](http://mysql-python.sourceforge.net/MySQLdb.html),把所有的參數都列出來,還有相關說明,請看官認真閱讀。不過,上面幾個是常用的,其它的看情況使用。
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.
已經完成了數據庫的連接。
- 第零章 預備
- 關于Python的故事
- 從小工到專家
- Python安裝
- 集成開發環境
- 第壹章 基本數據類型
- 數和四則運算
- 除法
- 常用數學函數和運算優先級
- 寫一個簡單的程序
- 字符串(1)
- 字符串(2)
- 字符串(3)
- 字符串(4)
- 字符編碼
- 列表(1)
- 列表(2)
- 列表(3)
- 回顧list和str
- 元組
- 字典(1)
- 字典(2)
- 集合(1)
- 集合(2)
- 第貳章 語句和文件
- 運算符
- 語句(1)
- 語句(2)
- 語句(3)
- 語句(4)
- 語句(5)
- 文件(1)
- 文件(2)
- 迭代
- 練習
- 自省
- 第叁章 函數
- 函數(1)
- 函數(2)
- 函數(3)
- 函數(4)
- 函數練習
- 第肆章 類
- 類(1)
- 類(2)
- 類(3)
- 類(4)
- 類(5)
- 多態和封裝
- 特殊方法(1)
- 特殊方法(2)
- 迭代器
- 生成器
- 上下文管理器
- 第伍章 錯誤和異常
- 錯誤和異常(1)
- 錯誤和異常(2)
- 錯誤和異常(3)
- 第陸章 模塊
- 編寫模塊
- 標準庫(1)
- 標準庫(2)
- 標準庫(3)
- 標準庫(4)
- 標準庫(5)
- 標準庫(6)
- 標準庫(7)
- 標準庫(8)
- 第三方庫
- 第柒章 保存數據
- 將數據存入文件
- mysql數據庫(1)
- MySQL數據庫(2)
- mongodb數據庫(1)
- SQLite數據庫
- 電子表格
- 第捌章 用Tornado做網站
- 為做網站而準備
- 分析Hello
- 用tornado做網站(1)
- 用tornado做網站(2)
- 用tornado做網站(3)
- 用tornado做網站(4)
- 用tornado做網站(5)
- 用tornado做網站(6)
- 用tornado做網站(7)
- 第玖章 科學計算
- 為計算做準備
- Pandas使用(1)
- Pandas使用(2)
- 處理股票數據
- 附:網絡文摘
- 如何成為Python高手
- ASCII、Unicode、GBK和UTF-8字符編碼的區別聯系