How to use the pymysql.err.InternalError function in PyMySQL

To help you get started, we’ve selected a few PyMySQL examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github paepcke / json_to_relation / scripts / testAllTruthFiles.py View on Github external
if testing:
            return
        self.mysqlDb = MySQLDB(user='paepcke')
        
	scriptDir = os.path.dirname(os.path.abspath(__file__))
	print scriptDir #****
	truthFilesDir = os.path.join(scriptDir, '../json_to_relation/test/data')
	print truthFilesDir #****
        for filename in os.listdir(truthFilesDir):
            if filename.endswith('Truth.sql'):
                print('Testing truth file %s' % filename)
                for sqlStatement in self.getSQLStatement(os.path.join(truthFilesDir, filename)):
                    try:
                        for res in self.mysqlDb.query(sqlStatement):
                            print res
                    except (pymysql.err.InternalError, pymysql.err.IntegrityError, pymysql.err.Error) as e:
                        print >>sys.stderr, 'Failed in filename %s: %s' % (filename, `e`)
        print 'Done.'
github DataDog / integrations-extras / proxysql / check.py View on Github external
try:
            with closing(conn.cursor()) as cursor:
                cursor.execute(sql)

                if cursor.rowcount < 1:
                    self.warning("Failed to fetch records from the stats schema 'stats_mysql_commands_counters' table.")
                    return None

                row = cursor.fetchone()

                return {
                    'Query_sum_time': row['query_sum_time_us'],
                    'Query_count': row['query_count']
                }
        except (pymysql.err.InternalError, pymysql.err.OperationalError) as e:
            self.warning("ProxySQL commands_counters stats unavailable at this time: %s" % str(e))
            return None
github frappe / frappe / frappe / database / mariadb / database.py View on Github external
from pymysql.times import TimeDelta
from pymysql.constants 	import ER, FIELD_TYPE
from pymysql.converters import conversions

from frappe.utils import get_datetime, cstr
from markdown2 import UnicodeWithAttrs
from frappe.database.database import Database
from six import PY2, binary_type, text_type, string_types
from frappe.database.mariadb.schema import MariaDBTable


class MariaDBDatabase(Database):
	ProgrammingError = pymysql.err.ProgrammingError
	TableMissingError = pymysql.err.ProgrammingError
	OperationalError = pymysql.err.OperationalError
	InternalError = pymysql.err.InternalError
	SQLError = pymysql.err.ProgrammingError
	DataError = pymysql.err.DataError
	REGEX_CHARACTER = 'regexp'

	def setup_type_map(self):
		self.db_type = 'mariadb'
		self.type_map = {
			'Currency':		('decimal', '18,6'),
			'Int':			('int', '11'),
			'Long Int':		('bigint', '20'),
			'Float':		('decimal', '18,6'),
			'Percent':		('decimal', '18,6'),
			'Check':		('int', '1'),
			'Small Text':	('text', ''),
			'Long Text':	('longtext', ''),
			'Code':			('longtext', ''),
github octans / PythonPractice / spiderWanghong / huajiao.py View on Github external
def replaceUserLive(data):
    try:
        kvs = dict()
        kvs['FLiveId'] = int(data['relateid'])
        kvs['FUserId'] = int(data['FUserId'])
        kvs['FWatches'] = int(data['watches'])
        kvs['FPraises'] = int(data['praises'])
        kvs['FReposts'] = int(data['reposts'])
        kvs['FReplies'] = int(data['replies'])
        kvs['FPublishTimestamp'] = int(data['publishtimestamp'])
        kvs['FTitle'] = data['title']
        kvs['FImage'] = data['image']
        kvs['FLocation'] = data['location']
        kvs['FScrapedTime'] = getNowTime()
        Live().insert(kvs, 1)
    except pymysql.err.InternalError as e:
        print(e)
github DataDog / dd-agent / checks.d / mysql.py View on Github external
def _is_innodb_engine_enabled(self, db):
        # Whether InnoDB engine is available or not can be found out either
        # from the output of SHOW ENGINES or from information_schema.ENGINES
        # table. Later is choosen because that involves no string parsing.
        try:
            with closing(db.cursor()) as cursor:
                cursor.execute(
                    "select engine from information_schema.ENGINES where engine='InnoDB' and \
                    support != 'no' and support != 'disabled'"
                )

                return (cursor.rowcount > 0)

        except (pymysql.err.InternalError, pymysql.err.OperationalError, pymysql.err.NotSupportedError) as e:
            self.warning("Possibly innodb stats unavailable - error querying engines table: %s" % str(e))
            return False
github datajoint / datajoint-python / datajoint / kill.py View on Github external
try:
                print('{ID:>4d} {USER:<12s} {STATE:<12s} {TIME:>5d}  {INFO}'.format(**process))
            except TypeError:
                print(process)
        response = input('process to kill or "q" to quit > ')
        if response == 'q':
            break
        if response:
            try:
                pid = int(response)
            except ValueError:
                pass  # ignore non-numeric input
            else:
                try:
                    connection.query('kill %d' % pid)
                except pymysql.err.InternalError:
                    print('Process not found')
github WordOps / WordOps / wo / core / mysql.py View on Github external
def connect(self):
        # Makes connection with MySQL server
        try:
            if os.path.exists('/etc/mysql/conf.d/my.cnf'):
                connection = \
                    pymysql.connect(read_default_file='/etc/mysql/'
                                    'conf.d/my.cnf')
            else:
                connection = pymysql.connect(read_default_file='~/.my.cnf')
            return connection
        except ValueError as e:
            Log.debug(self, str(e))
            raise MySQLConnectionError
        except pymysql.err.InternalError as e:
            Log.debug(self, str(e))
            raise MySQLConnectionError
github veelion / sanicdb / sanicdb.py View on Github external
async def get(self, query, *parameters, **kwparameters):
        """Returns the (singular) row returned by the given query.
        """
        if not self.pool:
            await self.init_pool()
        async with self.pool.acquire() as conn:
            async with conn.cursor() as cur:
                try:
                    await cur.execute(query, kwparameters or parameters)
                    ret = await cur.fetchone()
                except pymysql.err.InternalError:
                    await conn.ping()
                    await cur.execute(query, kwparameters or parameters)
                    ret = await cur.fetchone()
                return ret
github lb2281075105 / Python-Spider / 爬虫小demo / 01 taobao.py View on Github external
def get_connect(self):

        self.tablename = 'taobao'
        self.db = pymysql.connect(host='127.0.0.1', user='root', passwd='', db='test', charset='utf8')
        self.cur = self.db.cursor()
        self.cur.execute('USE test')
        try:
            # 创建表
            self.cur.execute('CREATE TABLE '+self.tablename+' (id BIGINT(7) NOT NULL AUTO_INCREMENT, name VARCHAR(100), city VARCHAR(20), height VARCHAR(10), weight VARCHAR(10), homepage VARCHAR(100), profile VARCHAR(100), pic VARCHAR(100), created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(id))')
        except pymysql.err.InternalError as e:
            print(e)
        # 修改表字段
        self.cur.execute('ALTER DATABASE test CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci')
        self.cur.execute('ALTER TABLE '+self.tablename+' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
        self.cur.execute('ALTER TABLE '+self.tablename+' CHANGE name name VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
        self.cur.execute('ALTER TABLE '+self.tablename+' CHANGE city city VARCHAR(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
        self.cur.execute('ALTER TABLE '+self.tablename+' CHANGE height height VARCHAR(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
        self.cur.execute('ALTER TABLE '+self.tablename+' CHANGE weight weight VARCHAR(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
        self.cur.execute('ALTER TABLE '+self.tablename+' CHANGE homepage homepage VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
        self.cur.execute('ALTER TABLE '+self.tablename+' CHANGE profile profile VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
        self.cur.execute('ALTER TABLE '+self.tablename+' CHANGE pic pic VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
github at7h / trod / helo / db.py View on Github external
def set(cls, key: str) -> None:
        if not isinstance(key, str):
            raise TypeError(f"invalid key type({key!r}), must be str")

        with cls._lock:
            cls.USER = key


class _ExcAdapter:
    """Exception adapter for pymysql"""

    _exc_map = {
        pymysql.err.Error: err.MySQLError,
        pymysql.err.DatabaseError: err.MySQLError,
        pymysql.err.MySQLError: err.MySQLError,
        pymysql.err.InternalError: err.MySQLError,
        pymysql.err.InterfaceError: err.InterfaceError,
        pymysql.err.DataError: err.MySQLDataError,
        pymysql.err.IntegrityError: err.IntegrityError,
        pymysql.err.NotSupportedError: err.NotSupportedError,
        pymysql.err.OperationalError: err.OperationalError,
        pymysql.err.ProgrammingError: err.ProgrammingError,
        pymysql.err.Warning: err.MySQLWarning,
    }  # type: Dict[Type[BaseException], Type[BaseException]]

    @classmethod
    def err(cls) -> BaseException:
        exc_type, exc_value, _traceback = sys.exc_info()
        if exc_type is not None:
            exc_cls = cls._exc_map.get(exc_type, exc_type)
            return exc_cls(exc_value)
        return err.ProgrammingError("No Exception info")