Python pymysql.Error() Examples

The following are 30 code examples of pymysql.Error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pymysql , or try the search function .
Example #1
Source File: test_sql.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def setup_method(self, request, datapath):
        pymysql = pytest.importorskip('pymysql')
        pymysql.connect(host='localhost', user='root', passwd='',
                        db='pandas_nosetest')
        try:
            pymysql.connect(read_default_group='pandas')
        except pymysql.ProgrammingError:
            raise RuntimeError(
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf.")
        except pymysql.Error:
            raise RuntimeError(
                "Cannot connect to database. "
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf.")

        self.method = request.function 
Example #2
Source File: test_sql.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def setup_class(cls):
        pymysql = pytest.importorskip('pymysql')
        pymysql.connect(host='localhost', user='root', passwd='',
                        db='pandas_nosetest')
        try:
            pymysql.connect(read_default_group='pandas')
        except pymysql.ProgrammingError:
            raise RuntimeError(
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf.")
        except pymysql.Error:
            raise RuntimeError(
                "Cannot connect to database. "
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf.") 
Example #3
Source File: peewee_async.py    From peewee-async with MIT License 6 votes vote down vote up
def select(query):
    """Perform SELECT query asynchronously.
    """
    assert isinstance(query, peewee.SelectQuery),\
        ("Error, trying to run select coroutine"
         "with wrong query class %s" % str(query))

    cursor = await _execute_query_async(query)

    result = AsyncQueryWrapper(cursor=cursor, query=query)

    try:
        while True:
            await result.fetchone()
    except GeneratorExit:
        pass
    finally:
        await cursor.release()

    return result 
Example #4
Source File: peewee_async.py    From peewee-async with MIT License 6 votes vote down vote up
def insert(query):
    """Perform INSERT query asynchronously. Returns last insert ID.
    This function is called by object.create for single objects only.
    """
    assert isinstance(query, peewee.Insert),\
        ("Error, trying to run insert coroutine"
         "with wrong query class %s" % str(query))

    cursor = await _execute_query_async(query)

    try:
        if query._returning:
            row = await cursor.fetchone()
            result = row[0]
        else:
            database = _query_db(query)
            last_id = await database.last_insert_id_async(cursor)
            result = last_id
    finally:
        await cursor.release()

    return result 
Example #5
Source File: peewee_async.py    From peewee-async with MIT License 6 votes vote down vote up
def raw_query(query):
    assert isinstance(query, peewee.RawQuery),\
        ("Error, trying to run raw_query coroutine"
         "with wrong query class %s" % str(query))

    cursor = await _execute_query_async(query)

    result = AsyncQueryWrapper(cursor=cursor, query=query)
    try:
        while True:
            await result.fetchone()
    except GeneratorExit:
        pass
    finally:
        await cursor.release()

    return result 
Example #6
Source File: mysql.py    From WordOps with MIT License 6 votes vote down vote up
def execute(self, statement, errormsg='', log=True):
        # Get login details from /etc/mysql/conf.d/my.cnf
        # & Execute MySQL query
        connection = WOMysql.connect(self)
        log and Log.debug(self, "Executing MySQL Statement : {0}"
                          .format(statement))
        try:
            cursor = connection.cursor()
            sql = statement
            cursor.execute(sql)

            # connection is not autocommit by default.
            # So you must commit to save your changes.
            connection.commit()
        except AttributeError as e:
            Log.debug(self, str(e))
            raise StatementExcecutionError
        except Error as e:
            Log.debug(self, str(e))
            raise StatementExcecutionError
        finally:
            connection.close() 
Example #7
Source File: mysql_repo.py    From monasca-notification with Apache License 2.0 6 votes vote down vote up
def fetch_notifications(self, alarm):
        try:
            if self._mysql is None:
                self._connect_to_mysql()
            cur = self._mysql.cursor()
            cur.execute(
                self._find_alarm_action_sql,
                (alarm['alarmDefinitionId'],
                 alarm['newState']))

            for row in cur:
                yield (row[0], row[1].lower(), row[2], row[3], row[4])
        except pymysql.Error as e:
            self._mysql = None
            log.exception("Couldn't fetch alarms actions %s", e)
            raise exc.DatabaseException(e) 
Example #8
Source File: mysql.py    From WordOps with MIT License 6 votes vote down vote up
def dbConnection(self, db_name):
        try:
            if os.path.exists('/etc/mysql/conf.d/my.cnf'):
                connection = pymysql.connect(
                    db=db_name, read_default_file='/etc/mysql/conf.d/my.cnf')
            else:
                connection = pymysql.connect(
                    db=db_name, read_default_file='~/.my.cnf')

            return connection
        except pymysql.err.InternalError as e:
            Log.debug(self, str(e))
            raise MySQLConnectionError
        except DatabaseError as e:
            if e.args[1] == '#42000Unknown database \'{0}\''.format(db_name):
                raise DatabaseNotExistsError
            else:
                raise MySQLConnectionError
        except Exception as e:
            Log.debug(self, "[Error]Setting up database: \'" + str(e) + "\'")
            raise MySQLConnectionError 
Example #9
Source File: peewee_async.py    From peewee-async with MIT License 6 votes vote down vote up
def allow_sync(self):
        """Allow sync queries within context. Close sync
        connection on exit if connected.

        Example::

            with database.allow_sync():
                PageBlock.create_table(True)
        """
        old_allow_sync = self._allow_sync
        self._allow_sync = True

        try:
            yield
        except:
            raise
        finally:
            try:
                self.close()
            except self.Error:
                pass  # already closed

        self._allow_sync = old_allow_sync 
Example #10
Source File: peewee_async.py    From peewee-async with MIT License 6 votes vote down vote up
def execute_sql(self, *args, **kwargs):
        """Sync execute SQL query, `allow_sync` must be set to True.
        """
        assert self._allow_sync, (
            "Error, sync query is not allowed! Call the `.set_allow_sync()` "
            "or use the `.allow_sync()` context manager.")
        if self._allow_sync in (logging.ERROR, logging.WARNING):
            logging.log(self._allow_sync,
                        "Error, sync query is not allowed: %s %s" %
                        (str(args), str(kwargs)))
        return super().execute_sql(*args, **kwargs)


##############
# PostgreSQL #
############## 
Example #11
Source File: application.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def redirect_url(encode_url):
    id = bases.fromBase62(encode_url)
    try:
        cursor.execute("SELECT URL FROM urls WHERE id = " + str(id))
        connection.commit()
        url = cursor.fetchone()
        return redirect(location=url[0])
    except pymysql.Error as e:
        print(str(e)) 
Example #12
Source File: peewee_async.py    From peewee-async with MIT License 5 votes vote down vote up
def init_async(self, conn_cls=AsyncPostgresqlConnection,
                   enable_json=False, enable_hstore=False):
        if not aiopg:
            raise Exception("Error, aiopg is not installed!")
        self._async_conn_cls = conn_cls
        self._enable_json = enable_json
        self._enable_hstore = enable_hstore 
Example #13
Source File: application.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def gen_short_url():
    long_url = request.form.get('long-url')
    try:
        cursor.execute("INSERT INTO urls (url) VALUES ('{}')".format(long_url))
        connection.commit()
    except pymysql.Error:
        raise
    # 获取自增id
    last_id = cursor.lastrowid
    encode = bases.toBase62(last_id)
    short_url = host + encode
    return render_template('index.html', short_url=short_url) 
Example #14
Source File: views.py    From autoops with Apache License 2.0 5 votes vote down vote up
def sql_rb(user, password, host, port, sequence, backup_dbname):  ##   查询回滚语句的表格

    port_a = int(port)
    connection = pymysql.connect(host=host, port=port_a, user=user, password=password, db=backup_dbname, charset="utf8",
                                 cursorclass=pymysql.cursors.DictCursor)
    connection1 = pymysql.connect(host=host, port=port_a, user=user, password=password, db=backup_dbname,
                                  charset="utf8",
                                  cursorclass=pymysql.cursors.DictCursor)

    try:
        with connection.cursor() as cursor:

            sql = " select  tablename   from  {0}.{1}  where opid_time ='{2}' ;".format(backup_dbname,  '$_$inception_backup_information$_$',sequence)
            cursor.execute(sql)
            result = cursor.fetchone()
            connection.commit()
            connection.close()
        table = result['tablename']

        try:
            with connection1.cursor() as cursor1:
                sql = " select rollback_statement  from  {0}.{1}  where opid_time = '{2}' ;".format(backup_dbname, table,sequence)
                cursor1.execute(sql)
                result1 = cursor1.fetchone()
                connection1.commit()
                connection1.close()


            ret = {"data": result1['rollback_statement']}
            return ret

        except Exception as e:
            data = "Mysql Error %d: %s" % (e.args[0], e.args[1])
            ret = {"data": data}
            return ret

    except Exception as e:
        data = "Mysql Error %d: %s" % (e.args[0], e.args[1])
        ret = data
        return ret 
Example #15
Source File: mysql_repo.py    From monasca-notification with Apache License 2.0 5 votes vote down vote up
def get_notification(self, notification_id):
        try:
            if self._mysql is None:
                self._connect_to_mysql()
            cur = self._mysql.cursor()
            cur.execute(self._get_notification_sql, notification_id)
            row = cur.fetchone()
            if row is None:
                return None
            else:
                return [row[0], row[1].lower(), row[2], row[3]]
        except pymysql.Error as e:
            self._mysql = None
            log.exception("Couldn't fetch the notification method %s", e)
            raise exc.DatabaseException(e) 
Example #16
Source File: test_mysql_repo.py    From monasca-notification with Apache License 2.0 5 votes vote down vote up
def testReconnect(self, mock_mysql):
        m = mock.MagicMock()

        m.cursor.side_effect = pymysql.Error

        mock_mysql.connect.return_value = m
        mock_mysql.Error = pymysql.Error

        repo = mysql_repo.MysqlRepo(base.config.CONF)

        alarm = {'alarmDefinitionId': 'foo',
                 'newState': 'bar'}

        def get_notification(repo, alarm):
            g = repo.fetch_notifications(alarm)
            for x in g:
                pass

        try:
            get_notification(repo, alarm)
        except exc.DatabaseException:
            try:
                get_notification(repo, alarm)
            except Exception:
                pass

        self.assertEqual(mock_mysql.connect.call_count, 2) 
Example #17
Source File: test_sql.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _close_conn(self):
        from pymysql.err import Error
        try:
            self.conn.close()
        except Error:
            pass 
Example #18
Source File: test_sql.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def setup_class(cls):
        _skip_if_no_pymysql()

        # test connection
        import pymysql
        try:
            # Try Travis defaults.
            # No real user should allow root access with a blank password.
            pymysql.connect(host='localhost', user='root', passwd='',
                            db='pandas_nosetest')
        except:
            pass
        else:
            return
        try:
            pymysql.connect(read_default_group='pandas')
        except pymysql.ProgrammingError:
            pytest.skip(
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf. ")
        except pymysql.Error:
            pytest.skip(
                "Cannot connect to database. "
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf. ") 
Example #19
Source File: test_sql.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def setup_method(self, method):
        _skip_if_no_pymysql()
        import pymysql
        try:
            # Try Travis defaults.
            # No real user should allow root access with a blank password.
            self.conn = pymysql.connect(host='localhost', user='root',
                                        passwd='', db='pandas_nosetest')
        except:
            pass
        else:
            return
        try:
            self.conn = pymysql.connect(read_default_group='pandas')
        except pymysql.ProgrammingError:
            pytest.skip(
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf. ")
        except pymysql.Error:
            pytest.skip(
                "Cannot connect to database. "
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf. ")

        self.method = method 
Example #20
Source File: scrapy_6v.py    From PT-help with MIT License 5 votes vote down vote up
def exec(self, sql: object, args: object = None, r_dict: object = False, fetch_all: object = False) -> object:
        with self._commit_lock:
            # The style of return info (dict or tuple)
            cursor = self.db.cursor(pymysql.cursors.DictCursor) if r_dict else self.db.cursor()
            row = cursor.execute(sql, args)
            try:
                self.db.commit()
                logging.debug("Success,DDL: \"{sql}\",Affect rows: {row}".format(sql=sql, row=row))
            except pymysql.Error as err:
                logging.critical("Mysql Error: \"{err}\",DDL: \"{sql}\"".format(err=err.args, sql=sql))
                self.db.rollback()

            # The lines of return info (one or all)
            return cursor.fetchall() if fetch_all else cursor.fetchone() 
Example #21
Source File: test_sql.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def _close_conn(self):
        from pymysql.err import Error
        try:
            self.conn.close()
        except Error:
            pass 
Example #22
Source File: test_sql.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def setup_class(cls):
        _skip_if_no_pymysql()

        # test connection
        import pymysql
        try:
            # Try Travis defaults.
            # No real user should allow root access with a blank password.
            pymysql.connect(host='localhost', user='root', passwd='',
                            db='pandas_nosetest')
        except:
            pass
        else:
            return
        try:
            pymysql.connect(read_default_group='pandas')
        except pymysql.ProgrammingError:
            pytest.skip(
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf. ")
        except pymysql.Error:
            pytest.skip(
                "Cannot connect to database. "
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf. ") 
Example #23
Source File: test_sql.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def setup_method(self, request, datapath):
        _skip_if_no_pymysql()
        import pymysql
        try:
            # Try Travis defaults.
            # No real user should allow root access with a blank password.
            self.conn = pymysql.connect(host='localhost', user='root',
                                        passwd='', db='pandas_nosetest')
        except:
            pass
        else:
            return
        try:
            self.conn = pymysql.connect(read_default_group='pandas')
        except pymysql.ProgrammingError:
            pytest.skip(
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf. ")
        except pymysql.Error:
            pytest.skip(
                "Cannot connect to database. "
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf. ")

        self.method = request.function 
Example #24
Source File: mysql_repo.py    From monasca-notification with Apache License 2.0 5 votes vote down vote up
def fetch_notification_method_types(self):
        try:
            if self._mysql is None:
                self._connect_to_mysql()
            cur = self._mysql.cursor()
            cur.execute(self._find_all_notification_types_sql)

            for row in cur:
                yield (row[0])
        except pymysql.Error as e:
            self._mysql = None
            log.exception("Couldn't fetch notification types %s", e)
            raise exc.DatabaseException(e) 
Example #25
Source File: checker.py    From root-2015-tasks with GNU General Public License v3.0 5 votes vote down vote up
def check(connection):
    cursor = connection.cursor()
    try:
        test_query(cursor, 'SELECT COUNT(*) FROM db.data WHERE size < 10',
                   444724, 3.0)
        test_query(cursor, 'SELECT MAX(hits) FROM db.data',
                   12252257, 3.0)
        test_query(cursor,
                   'SELECT hits FROM db.data ORDER BY hits DESC LIMIT 10',
                   64165894, 3.0)
    except mariadb.Error as e:
        done(STATUS_NOT_OK, str(e), e)
    finally:
        cursor.close() 
Example #26
Source File: checker.py    From root-2015-tasks with GNU General Public License v3.0 5 votes vote down vote up
def main():
    ip = sys.argv[1]
    try:
        db = mariadb.connect(host=ip, user=USER, password=PASS)
    except mariadb.Error as e:
        done(STATUS_NOT_OK, str(e), e)

    try:
        check(db)
    finally:
        db.close()

    done(STATUS_OK) 
Example #27
Source File: peewee_async.py    From peewee-async with MIT License 5 votes vote down vote up
def connect_async(self, loop=None, timeout=None):
        """Set up async connection on specified event loop or
        on default event loop.
        """
        if self.deferred:
            raise Exception("Error, database not properly initialized "
                            "before opening connection")

        if self._async_conn:
            return
        elif self._async_wait:
            await self._async_wait
        else:
            self._loop = loop
            self._async_wait = asyncio.Future(loop=self._loop)

            if not timeout and self._timeout:
                timeout = self._timeout

            conn = self._async_conn_cls(
                database=self.database,
                loop=self._loop,
                timeout=timeout,
                **self.connect_params_async)

            try:
                await conn.connect()
            except Exception as e:
                if not self._async_wait.done():
                    self._async_wait.set_exception(e)
                self._async_wait = None
                raise
            else:
                self._task_data = TaskLocals(loop=self._loop)
                self._async_conn = conn
                self._async_wait.set_result(True) 
Example #28
Source File: peewee_async.py    From peewee-async with MIT License 5 votes vote down vote up
def update(query):
    """Perform UPDATE query asynchronously. Returns number of rows updated.
    """
    assert isinstance(query, peewee.Update),\
        ("Error, trying to run update coroutine"
         "with wrong query class %s" % str(query))

    cursor = await _execute_query_async(query)
    rowcount = cursor.rowcount

    await cursor.release()
    return rowcount 
Example #29
Source File: peewee_async.py    From peewee-async with MIT License 5 votes vote down vote up
def _swap_database(self, query):
        """Swap database for query if swappable. Return **new query**
        with swapped database.

        This is experimental feature which allows us to have multiple
        managers configured against different databases for single model
        definition.

        The essential limitation though is that database backend have
        to be **the same type** for model and manager!
        """
        database = _query_db(query)

        if database == self.database:
            return query

        if self._subclassed(peewee.PostgresqlDatabase, database,
                            self.database):
            can_swap = True
        elif self._subclassed(peewee.MySQLDatabase, database,
                              self.database):
            can_swap = True
        else:
            can_swap = False

        if can_swap:
            # **Experimental** database swapping!
            query = query.clone()
            query._database = self.database
            return query

        assert False, (
            "Error, query's database and manager's database are "
            "different. Query: %s Manager: %s" % (database, self.database)
        )

        return None 
Example #30
Source File: peewee_async.py    From peewee-async with MIT License 5 votes vote down vote up
def __init__(self, database=None, *, loop=None):
        assert database or self.database, \
               ("Error, database must be provided via "
                "argument or class member.")

        self.database = database or self.database
        self._loop = loop
        self._timeout = getattr(database, 'timeout', None)

        attach_callback = getattr(self.database, 'attach_callback', None)
        if attach_callback:
            attach_callback(lambda db: setattr(db, '_loop', loop))
        else:
            self.database._loop = loop