为python2和python3安装MySQL--python的交互 sudo apt-get install python-mysqldb
sudo apt-get install python3-mysqldb import MySQL 导入不出错就可以了 封装代码:
#encoding=utf8import MySQLdbclass MysqlHelper(): def __init__(self,host,port,db,user,passwd,charset='utf8'): self.host=host self.port=port self.db=db self.user=user self.passwd=passwd self.charset=charset def connect(self): self.conn=MySQLdb.connect(host=self.host,port=self.port,db=self.db,user=self.user,passwd=self.passwd,charset=self.charset) self.cursor=self.conn.cursor() def close(self): self.cursor.close() self.conn.close() def get_one(self,sql,params=()): result=None try: self.connect() self.cursor.execute(sql, params) result = self.cursor.fetchone() self.close() except Exception, e: print e.message return result def get_all(self,sql,params=()): list=() try: self.connect() self.cursor.execute(sql,params) list=self.cursor.fetchall() self.close() except Exception,e: print e.message return list def insert(self,sql,params=()): return self.__edit(sql,params) def update(self, sql, params=()): return self.__edit(sql, params) def delete(self, sql, params=()): return self.__edit(sql, params) def __edit(self,sql,params): count=0 try: self.connect() count=self.cursor.execute(sql,params) self.conn.commit() self.close() except Exception,e: print e.message return count