Python学习笔记9-Python 链接MySql数据库

时间:2021-10-16 06:29:08

Python 链接MySql数据库,方法很简单:

首先需要先 安装一个MySql链接插件:MySQL-python-1.2.3.win-amd64-py2.7.exe

下载地址:http://dev.mysql.com/downloads/connector/python/

在下载安装的时候,最好与Python的版本相对应,否则会有些功能不能使用;

在安装完成以后,可以在Python的目录下面看到相应的插件:

Python27/Lib/site-packages

Python学习笔记9-Python 链接MySql数据库

如何测试是否安装成功?

方法1 :cmd -》python -》import MySQLdb 如果没报错,就是安装成功了;

Python学习笔记9-Python 链接MySql数据库

方法2:在eclipse 的文件中输入 import MySQLdb 如果有智能提示,说明安装成功了;

Python学习笔记9-Python 链接MySql数据库

安装成功了,我们马上来试一下效果吧:

#--encoding:utf-8--
#
import MySQLdb
import datetime con = MySQLdb.connect(host='localhost',user='root',passwd='',db='employee')
con.set_character_set('utf8')
cursor =con.cursor()
# 查询操作
sql ="select * from users"
cursor.execute(sql)
rows=cursor.fetchall() for row in rows:
print row[0],row[1],row[2] cursor.close()
con.close()

将代码中的sql和数据库换成自己的,快去试一下吧!