MySQL 是十分流行的開源資料庫系統,很多網站也是使用 MySQL 作為後台資料儲存,而 Python 要連接 MySQL 可以使用 MySQL 模組。MySQLdb 模組可以讓 Python 程式連線到 MySQL server, 執行 SQL 語句及擷取資料等。
開始前要確定系統內的 Python 有安裝 MySQLdb 模式,你可以 Python command line interpreter 檢查,在指令模式輸入 python,然後便可以開始檢查:
|
1 2 3 4 5 6 7 8 |
Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb Traceback (most recent call last): File "", line 1, in ImportError: No module named MySQLdb >>> exit() |
如果見以上面的 “ImportError: No module named MySQLdb” 一句,便表示系統沒有安裝,到 MySQLdb 官方網站 下載 MySQLdb,並用以下方法安裝:
|
1 2 3 4 |
$ tar zxvf MySQL-python-1.2.2.tar.gz $ cd MySQL-python-1.2.2 $ python setup.py build $ python setup.py install |
安裝好 MySQLdb 後便可以編寫程式碼,以下是簡單的例子:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#!/usr/bin/python # 引入 MySQL 模組 import MySQLdb # 連接到 MySQL db = MySQLdb.connect(host="localhost", user="db_user", passwd="db_pass", db="db_name") cursor = db.cursor() # 執行 SQL 語句 cursor.execute("SELECT * FROM db_table") result = cursor.fetchall() # 輸出結果 for record in result: print record[0] |
請問途中的dbname代表什麼意思
即資料庫名稱.