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

Python 学习入门(4)—— 连接 MySQL

下载 MySQL for Python,最新版 MySQL-python-1.2.4b4.tar.gz


1) 提前安装:mysql_config 环境

否则后面 python setup.py build 会提示找不到 “EnvironmentError: mysql_config not found”,安装命令如下:

sudo apt-get install libmysqlclient-dev


2) 然后,再安装MySQLdb

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


3) 验证成功安装

homer@ubuntu:~/myCode/python$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
import MySQLdb
>>> 

import MySQLdb 没有出错,说明安装成功!



python 连接mysql示例:

####################
# IT-Homer
# 2013-05-10
####################


import MySQLdb


db = MySQLdb.connect(host="localhost", user="root", passwd="abcd1234", db="testDB")

cursor = db.cursor()

cursor.execute("Select * from gameTestDB limit 10")
result = cursor.fetchall()

for row in result:
  #print row
  #print row[0], row[1], row[2]
  #print '%s, %s, %s' % (row[0], row[1], row[2])
  print ', '.join([str(row[0]), str(row[1]), str(row[2])])

cursor.close()



'''
import sys
import MySQLdb

reload(sys)
sys.setdefaultencoding('utf-8')


db = MySQLdb.connect(user='root', passwd='abcd1234', charset='utf8')
cur = db.cursor()
cur.execute('use testDB')
cur.execute('select * from gameTestDB limit 10')

f = file("/home/homer/tmp_mysql.txt", 'w')

for row in cur.fetchall():
  f.write(str(row))
  f.write("\n")

f.close()
cur.close()
'''


####################
# IT-Homer
# 2013-05-10
####################


import MySQLdb

# local mysql
# db = MySQLdb.connect(host="localhost", user="root", passwd="abcd1234", db="testDB")

# aws rds mysql
db = MySQLdb.connect(host="ithomer.aliyun.com", user="ithomer", passwd="abcd1234", db="dman")

cursor = db.cursor()

cursor.execute("Select * from score limit 10")
result = cursor.fetchall()

for row in result:
  #print row
  #print row[0], row[1], row[2]
  #print '%s, %s, %s' % (row[0], row[1], row[2])
  print ', '.join([str(row[0]), str(row[1]), str(row[2])])

cursor.close()



'''
import sys
import MySQLdb

reload(sys)
sys.setdefaultencoding('utf-8')


db = MySQLdb.connect(user='root', passwd='abcd1234', charset='utf8')
cur = db.cursor()
cu