Python:安裝setuptools,安裝MySQLdb模組,連線資料庫程式碼
一、準備工作
安裝MySQLdb需要事先安裝以下元件:
1.1 python
yum install python-devel
1.2 mysql
yum install mysql-devel
1.3 gcc
yum install gcc
1.4 setuptools
當需要安裝第三方python包時,可能會用到easy_install命令。
easy_install是由PEAK(Python Enterprise Application Kit)開發的setuptools包裡帶的一個命令,所以使用easy_install實際上是在呼叫setuptools來完成安裝模組的工作。
檔名:setuptools-18.3.1.tar.gz
下載地址:https://pypi.python.org/pypi/setuptools#downloads
tar zxvf setuptools-18.3.1.tar.gz
cd setuptools-18.3.1
python setup.py build
python setup.py install
二、下載、安裝MySQLdb
2.1 下載、安裝MySQLdb
檔名:MySQL-python-1.2.3.tar.gz
下載地址:http://sourceforge.net/projects/mysql-python/ "Browse All Files" "mysql-python" "1.2.3" "MySQL-python-1.2.3.tar.gz"
http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/
wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz
tar zxvf MySQL-python-1.2.3.tar.gz
cd MySQL-python-1.2.3
python setup.py build
python setup.py install
2.2 檢視MySQLdb是否安裝成功
import MySQLdb
出現下面介面,說明沒有安裝MySQLdb:
三、連線資料庫例項
3.1 程式碼
#!/usr/bin/env python
import MySQLdb
conn = MySQLdb.connect(host="localhost", user="root", passwd="love", db="inerdns", port = 3306, connect_timeout=15)
cur = conn.cursor()
cur.execute("select * from probe_result")
rows = cur.fetchall()
for row in rows:
print row
for r in row:
print r
cur.close()
conn.close()
3.2 執行結果
參考資料: