mac下安装MySQL-python

本文档提供了一种详细的步骤来解决Python环境下MySQL数据库连接及操作的问题,包括卸载旧版驱动、安装新版驱动以及使用Python脚本进行数据库操作的方法。此外还提供了常见错误的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 先把之前装的卸载干净:
    pip uninstall mysql-python
    brew uninstall mysql-connector-c
  • 安装
    brew install mysql-connector-c
    pip install mysql-python

  • 还有中文编码的1366错误,大家也可以看一下.

下边是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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值