用Python來編寫網站,必須要能夠通過python操作數據庫,所謂操作數據庫,就是通過python實現對數據的連接,以及對記錄、字段的各種操作。上一講提到的那種操作方式,是看官直接通過交互模式來操作數據庫。
## 安裝python-MySQLdb
要想通過python來操作數據庫,還需要在已經安裝了mysql的基礎上安裝一個稱之為mysqldb的庫,它是一個接口程序,python通過它對mysql數據實現各種操作。
在編程中,會遇到很多類似的接口程序,通過接口程序對另外一個對象進行操作,比較簡單。接口程序就好比鑰匙,如果要開鎖,人直接用手指去捅,肯定是不行的,那么必須借助工具,插入到鎖孔中,把所打開,打開所之后,門開了,就可以操作門里面的東西了。那么打開所的工具就是接口程序。而打開所的工具會有便利與否之分,如果用這鎖的鑰匙,就便利,如果用別的工具,或許不便利(其實還分人,也就是人開鎖的水平,如果是江洋大盜或者小毛賊什么的,擅長開鎖,用別的工具也便利了),也就是接口程序不同,編碼水平不同,都是考慮因素。
這里下載python-mysqldb:[https://pypi.python.org/pypi/MySQL-python/](https://pypi.python.org/pypi/MySQL-python/)
下載之后就可以安裝了。
我這里只能演示ubuntu下安裝的過程。
~~~
sudo apt-get install python-MySQLdb
~~~
在shell中輸入上面的命令行,就安裝了。看看,多么簡潔的安裝,請快快用ubuntu吧。我愿意做ubuntu的免費代言。哈哈。
不管什么系統,安裝不是難題。安裝之后,怎么知道安裝的結果呢?
~~~
>>> import MySQLdb
~~~
在python的交互模式中,輸入上面的指令,如果不報錯,恭喜你,已經安裝好了。如果報錯,恭喜你,可以借著錯誤信息提高自己的計算機水平了,請求助于google大神。
## 交互模式下操作數據庫之連接數據庫
操作數據庫的前提是先有數據庫。
先建立一個數據庫。
~~~
qw@qw-Latitude-E4300:~$ 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的庫了。進入到python交互模式(現在這個實驗室做實驗)。
~~~
>>> 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環境安裝
- 集成開發環境(IDE)
- 數的類型和四則運算
- 啰嗦的除法
- 開始真正編程
- 初識永遠強大的函數
- 玩轉字符串(1):基本概念、字符轉義、字符串連接、變量與字符串關系
- 玩轉字符串(2)
- 玩轉字符串(3)
- 眼花繚亂的運算符
- 從if開始語句的征程
- 一個免費的實驗室
- 有容乃大的list(1)
- 有容乃大的list(2)
- 有容乃大的list(3)
- 有容乃大的list(4)
- list和str比較
- 畫圈還不簡單嗎
- 再深點,更懂list
- 字典,你還記得嗎?
- 字典的操作方法
- 有點簡約的元組
- 一二三,集合了
- 集合的關系
- Python數據類型總結
- 深入變量和引用對象
- 賦值,簡單也不簡單
- 坑爹的字符編碼
- 做一個小游戲
- 不要紅頭文件(1): open, write, close
- 不要紅頭文件(2): os.stat, closed, mode, read, readlines, readline
- 第二部分 窮千里目,上一層樓
- 正規地說一句話
- print能干的事情
- 從格式化表達式到方法
- 復習if語句
- 用while來循環
- 難以想象的for
- 關于循環的小伎倆
- 讓人歡喜讓人憂的迭代
- 大話題小函數(1)
- 大話題小函數(2)
- python文檔
- 重回函數
- 變量和參數
- 總結參數的傳遞
- 傳說中的函數條規
- 關于類的基本認識
- 編寫類之一創建實例
- 編寫類之二方法
- 編寫類之三子類
- 編寫類之四再論繼承
- 命名空間
- 類的細節
- Import 模塊
- 模塊的加載
- 私有和專有
- 折騰一下目錄: os.path.<attribute>
- 第三部分 昨夜西風,亭臺誰登
- 網站的結構:網站組成、MySQL數據庫的安裝和配置、MySQL的運行
- 通過Python連接數據庫:安裝python-MySQLdb,連接MySQL
- 用Pyton操作數據庫(1):建立連接和游標,并insert and commit
- 用Python操作數據庫(2)
- 用Python操作數據庫(3)
- python開發框架:框架介紹、Tornado安裝
- Hello,第一個網頁分析:tornado網站的基本結構剖析:improt模塊、RequestHandler, HTTPServer, Application, IOLoop
- 實例分析get和post:get()通過URL得到數據和post()通過get_argument()獲取數據
- 問候世界:利用GAE建立tornado框架網站
- 使用表單和模板:tornado模板self.render和模板變量傳遞
- 模板中的語法:tornado模板中的for,if,set等語法
- 靜態文件以及一個項目框架
- 模板轉義
- 第四部分 暮然回首,燈火闌珊處
- requests庫
- 比較json/dictionary的庫
- defaultdict 模塊和 namedtuple 模塊
- 第五部分 Python備忘錄
- 基本的(字面量)值
- 運算符
- 常用的內建函數
- 擴展閱讀(來自網絡文章)
- 人生苦短,我用Python