關於 PHP, Linux, Open Source 及個人生活記載的網誌。
RSS icon
  • Python 連接 MySQL

    Posted on August 20th, 2007 Sam Tang 2 comments

    MySQL 是十分流行的開源資料庫系統,很多網站也是使用 MySQL 作為後台資料儲存,而 Python 要連接 MySQL 可以使用 MySQL 模組。MySQLdb 模組可以讓 Python 程式連線到 MySQL server, 執行 SQL 語句及擷取資料等。

    開始前要確定系統內的 Python 有安裝 MySQLdb 模式,你可以 Python command line interpreter 檢查,在指令模式輸入 python,然後便可以開始檢查:

    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,並用以下方法安裝:

    $ tar zxvf MySQL-python-1.2.2.tar.gz
    $ cd MySQL-python-1.2.2
    $ python setup.py build
    $ python setup.py install

     
    安裝好 MySQLdb 後便可以編寫程式碼,以下是簡單的例子:

    CODE:
    1. #!/usr/bin/python
    2.  
    3. # 引入 MySQL 模組
    4. import MySQLdb
    5.  
    6. # 連接到 MySQL
    7. db = MySQLdb.connect(host="localhost", user="db_user", passwd="db_pass", db="db_name")
    8. cursor = db.cursor()
    9.  
    10. # 執行 SQL 語句
    11. cursor.execute("SELECT * FROM db_table")
    12. result = cursor.fetchall()
    13.  
    14. # 輸出結果
    15. for record in result:
    16.     print record[0]


     

    2 responses to “Python 連接 MySQL”

    1. 你好,非常感谢你的分享精神,很仔细。
      但是我有一个疑问,当你在执行从数据库提取资料的操作时,突然断线了怎么办,用什么方法让它实现断线重连呢?
      ps:断线的原因有很多种,不仅仅局限于服务器重启。

    2. another_python_fan

      @python爱好者:

      You might be interested in this:

      http://stackoverflow.com/questions/207981/how-to-enable-mysql-client-auto-re-connect-with-mysqldb

      and this patch:

      https://bugs.launchpad.net/ubuntu/+source/python-mysqldb/+bug/163184

      Good luck.

    Leave a reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word