• 先把之前装的卸载干净:
    pip uninstall mysql-python
    brew uninstall mysql-connector-c
  • 安装
    brew install mysql-connector-c
    pip install mysql-python
  • 还有中文编码的1366错误,大家也可以看一下.

​http://fengmm521.blog.163.com/blog/static/25091358201712374927826/​


下边是python访问mysql数据库的例子代码:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
import time
from subprocess import Popen,PIPE

class mysqlobj():
def __init__(self,addr = 'localhost',port = 3306,usname = 'root',uspw = '123456',defDB = 'test'):
self.mysqladdr = addr #mysql地址
self.mysqlport = port #mysql端口
self.mysqlusername = usname #mysql登陆用户名
self.mysqlpassword = uspw #mysql登陆密码
self.mysqlDefaleDB = defDB #mysql默认登陆数据库
self.connectManger = None #mysql连接管理器
self.mysqlcursor = None #mysql消息收发器
self.connectMysql() #连接mysql数据库

def connectMysql(self):
self.connectManger = MySQLdb.connect(
host = self.mysqladdr,
port = self.mysqlport,
user = self.mysqlusername,
passwd = self.mysqlpassword,
db = self.mysqlDefaleDB,
charset="utf8". #注意这里的utf8命令编码格式要设置
)
self.mysqlcursor = self.connectManger.cursor()
#调用mysql命令
def execute(self,cmdstr,isCommit = True):
try:
self.connectManger.ping()
except:
self.connectMysql()
if self.mysqlcursor:
print 'mysqlask:%s'%(cmdstr)
try:
tmp = self.mysqlcursor.execute(cmdstr)
if isCommit:
self.connectManger.commit()
except MySQLdb.Error, e:
print MySQLdb.Error,e,time.ctime(time.time())
if MySQLdb.Error == 2006:
self.connectMysql()
print MySQLdb.Error
if MySQLdb.Error and e[0] == 1050:#数据表已存在,表创建错误
print '数据表已存在,mysql错误码:1050'
return 1050
elif MySQLdb.Error and e[0] == 2014:
self.mysqlcursor.close()
self.mysqlcursor= self.connectManger.cursor()
return 2014
else:
tmp = self.mysqlcursor.execute(cmdstr)
if isCommit:
self.connectManger.commit()
return tmp
else:
return -999#mysql 未连接 #使用.sql文件
def inPutDataWithSqlFile(self,sqlfilepath):
process = Popen('/usr/local/mysql/bin/mysql -h%s -P%s -u%s -p%s %s' %(self.mysqladdr, self.mysqlport, self.mysqlusername, self.mysqlpassword, self.mysqlDefaleDB), stdout=PIPE, stdin=PIPE, shell=True)
output = process.communicate('source '+sqlfilepath)
print output