日期:2014-05-16  浏览次数:20703 次

linux下 python连接mysql 入门

1. 环境安装

yum -y install python.x86_64
yum -y install MySQL-python.x86_64

?

2. 测试demo

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import os,sys
import  MySQLdb

try:
   db = MySQLdb.connect(host ='10.232.31.33', user='xxx', passwd='xxx', db ='xxx')
except MySQLdb.ERROR,e:
   print "Error %d:%s"%(e.args[0],e.args[1])
   exit(1)
cursor = db.cursor()
cursor.execute('select * from xxx_task')
result_set=cursor.fetchall()
print result_set
cursor.close()
db.close()

? ?将例子保存为test.py

?

3. 执行

? ?$chmod +x test.py

? ?$python ?test.py

? ? 如果看到有记录输出,说明连接成功了!

?

?