1、配置MySLQ
1-1:安装mysql windows 安装mysql5.7
1-2:安装python依赖mysql模块
pip install mysql 安装Python的MySQL库,但是总会报错。
常见错误如:
Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat)
mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
这些可能是驱动等问题。
本文章采用下面的方法安装:
下载一个MySQL-python-1.2.3.win-amd64-py2.7.exe文件进行安装。
官网地址:https://pypi.python.org/pypi/MySQL-python/
下载地址:http://download.csdn.net/detail/eastmount/9598651
默认安装即可。
2、引入MySQLdb库,如下:
import MySQLdb
3、连接数据路
conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test2', charset='utf8')
- user:Username
- password:Password
- host:Hostname
- database:DatabaseName
- lose():关闭数据库连接,或者关闭游标对象
- commit():提交当前事务
- rollback():取消当前事务
- cursor():创建游标或类游标对象
- errorhandler(cxn,errcls,errval):作为已给游标的句
游标对象:
fetchone():可以看作fetch(取出) one(一个),也就是得到结果集的下一行(一行)。
fetchmany(size):可以看作fetch(取出)many(多个),这里的参数是界限,得到结果集的下几行(几行)fetchall():顾名思义,取得所有。
execute(sql):执行数据库操作,参数为sql语句。
close():不需要游标时尽可能的关闭
下面是整个python连接mysql实例
# coding:utf-8
import MySQLdb
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306)
cur=conn.cursor()
res = cur.execute('show databases')
print res
for data in cur.fetchall():
print '%s' % data
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
查询数据并写入mysqlDB文件:
import MySQLdb
import datetime
import time
def isDate(datetime):
try:
datetime.strftime('%Y-%m-%d')
return True
except Exception as e:
return False
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306,db='test2')
cur=conn.cursor()
res = cur.execute('select * from t_user')
print res
for data in cur.fetchall():
for x in data:
if isDate(x):
if x=='':
x='NULL'
open('userDB.txt','a+').write(x.strftime('%Y-%m-%d')+"\n")
else:
if x=='':
x='NULL'
open('userDB.txt','a+').write(x+"\n")
print x
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])