Python学习入门(4)-连接MySQL下载MySQL for Python,MySQL-python-1.2.4b4.tar.gz最新版本1)提前安装:mysql_config环境或python setup.py build会提示“环境错误:找不到MySQL _ config”找不到。安装命令如下:sudo apt-ge。
Python学习入门(四)-连接MySQL下载MySQL for Python,MySQL-python-1.2.4b4.tar.gz最新版本。
1)预先安装:mysql_config环境
否则python setup.py build会提示“环境错误:找不到MySQL _ config”找不到。安装命令如下:
sudo apt-get install libmysql client-dev
2)然后,安装MySQLdb。
$ tar zxvf MySQL-python-1 . 2 . 2 . 2 . tar . gz
$ CD MySQL-python-1 . 2 . 2
$ sudo python setup . py build
$ sudo python setup . py install
3)验证安装是否成功
homer @ Ubuntu:~/my code/Python $ Python
Python 2 . 7 . 3(默认,2012年8月1日05:14:39)
[GCC 4.6.3]在linux2上
键入" help "、" copyright "、" credits "或" license "以获取更多信息。
> > >导入MySQLdb
> >
导入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() 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用户指南
Python字符串操作
未找到mysql_config(堆栈流)
Python创建了mysql数据库