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] |