python连接mysql异常的简单介绍

发布时间:2022-11-16

本文目录一览:

  1. MySQL-python连接MySQL数据库问题,总是抛异常。
  2. python连接mysql数据库出错,已经尝试了网上的几种解决方法
  3. python 连接mysql 时,connect 出现错误,怎么解决

MySQL-python连接MySQL数据库问题,总是抛异常。

不要刚开始学多线程编程就这样玩。connectioncursor 都不是线程安全的。 如果测试环境用多个线程,每个线程要在线程里面获取自己的 connection,然后从这个 connection 获取 cursor。 如果生产环境用多个线程,建议使用线程安全的连接池。

python连接mysql数据库出错,已经尝试了网上的几种解决方法

这里的意思是:数据库连不上啊。 可能是网络问题,可能是防火墙问题,可能是3306端口没开。你先排除这些问题吧。用一些mysql工具连接测试看,比如SQLyog 测试。

python 连接mysql 时,connect 出现错误,怎么解决

# -*- coding: utf-8 -*-
import MySQLdb
from MySQLdb.cursors import DictCursor
def catch_2006(func):
    """
    To catch MySQL Error 2006 ('Server has gone away')
    """
    def _(self, *args, **kwargs):
        try:
            return func(self, *args, **kwargs)
        except MySQLdb.Error, e:
            print __file__, e
            if e.args[0] == 2006 or e.args[0] == 0:
                self.reboot_conn()
                return func(self, *args, **kwargs)
            # todo
            # How to deal if not the code
    return _
class DB(object):
    def __init__(self, host, port, user, passwd, db, use_unicode=True, charset='utf8'):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.db = db
        self.use_unicode = use_unicode
        self.charset = charset
    @property
    def conn(self):
        if not hasattr(self, '__conn'):
            self.__conn = MySQLdb.connect(
                host=self.host,
                port=self.port,
                user=self.user,
                passwd=self.passwd,
                db=self.db,
                use_unicode=self.use_unicode,
                charset=self.charset
            )
        return self.__conn
    def reboot_conn(self):
        if hasattr(self, '__conn'):
            try:
                self.__conn.close()
                del self.__conn
            except:
                pass
    @catch_2006
    def query(self, sql, args=None):
        print sql
        cursor = self.conn.cursor()
        cursor.execute(sql, args)
        cursor.execute('commit')
        cursor.close()
    @catch_2006
    def select(self, sql, args=None, is_dict=False, is_one=False):
        # print sql, args
        if is_dict:
            cursor = self.conn.cursor(cursorclass=DictCursor)
        else:
            cursor = self.conn.cursor()
        cursor.execute(sql, args)
        if is_one:
            resultset = cursor.fetchone()[0]
        else:
            resultset = cursor.fetchall()
        cursor.close()
        return resultset

这个是我以前项目中使用Python链接MySQL的例子,你可以参考一下。 如果解决了您的问题请采纳! 如果未解决请继续追问!