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

  • 内容
  • 评论
  • 相关

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() ''' 

欢迎大家阅读《Python 学习入门(四)—— 连接 MySQL》,跪求各位点评,by 搞代码

#################### # 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() 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() 

参考推荐:

Python 連接 MySQL

MySQLdb User's Guide

Python 字符串操作

mysql_config not found(stackover flow)

python 创建mysql数据库

原创文章,转载请注明: 转载自搞代码

本文链接地址: Python 学习入门(四)—— 连接 MySQL

微信支付二维码

微信 赏一包辣条吧~

支付宝支付二维码

支付宝 赏一听可乐吧~

评论

0条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注