环境 python2.7+Win
1.安装MySQldb模块
访问:http://www.lfd.uci.edu/~gohlke/pythonlibs/
下载MySQL_python-1.2.5-cp27-none-win_amd64.whl(32位64位自行选择)
将其拷贝到python安装目录下的Scripts目录下,在文件位置打开cmd,执行pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl
验证,python(command line)输入import MySQLdb,没报错,说明安装成功。
参考:http://blog.csdn.net/fgwvip123/article/details/52382521
2.Python操作MySQL数据库
# -*- coding: UTF-8 -*-
# 基本操作
import MySQLdb
# 打开数据库连接,首先需要创建一个test数据库
db = MySQLdb.connect("127.0.0.1","账号","密码","test")
# 使用cursor方法获取操作光标,cursor(光标)
cursor = db.cursor()
# 使用execute方法执行sql语句,execute(执行)
cursor.execute("select version()")
# fetch(获取)one,all
data = cursor.fetchone()
print "Database version: %s" % data
# -*- coding: UTF-8 -*-
# 插入数据
import MySQLdb
name = "testname"
password = "testpasss"
# 打开数据库连接,首先需要创建一个test数据库
db = MySQLdb.connect("127.0.0.1","账号","密码","test")
# 使用cursor方法获取操作光标,cursor(光标)
cursor = db.cursor()
# sql语句
sql = '''insert into user(name, password)
values ("%s", "%s")''' % (name,password)
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误,未commit之前回滚
db.rollback()
db.close()
参考:
菜鸟教程:http://www.runoob.com/python/python-mysql.html
官方手册:http://mysql-python.sourceforge.net/MySQLdb.html