本文整理匯總了Python中pymysql.Error方法的典型用法代碼示例。如果您正苦於以下問題:Python pymysql.Error方法的具體用法?Python pymysql.Error怎麽用?Python pymysql.Error使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pymysql
的用法示例。
在下文中一共展示了pymysql.Error方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: insertCrawlerHtml
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
def insertCrawlerHtml(self, new_dict):
try:
sql = "insert into crawler_html " \
"(hub_id,html_url,state,create_date) " \
"VALUES " \
"(%s,'%s','%s','%s')" \
% (new_dict['hub_id'], new_dict['html_url'], new_dict['state'], new_dict['create_date'])
try:
# logger.getDebugLog(sql)
result = self.cursor.execute(sql)
self.conn.commit()
if result:
logger.getDebugLog("MySQLCommand-insertCrawlerHtml-插入[crawler_html]成功")
except pymysql.Error as e:
self.conn.rollback()
logger.getErrorLog(
"MySQLCommand-insertCrawlerHtml-插入[crawler_html]失敗,原因 %d: %s" % (e.args[0], e.args[1]))
except pymysql.Error as e:
logger.getErrorLog("MySQLCommand-insertCrawlerHtml-數據庫錯誤,原因%d: %s" % (e.args[0], e.args[1]))
# 將文章信息插入crawler_article並更新crawler_html的狀態
示例2: dbConnection
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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
示例3: execute
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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()
示例4: setup_class
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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.")
示例5: setup_method
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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
示例6: select
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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
示例7: insert
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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
示例8: raw_query
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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
示例9: allow_sync
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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
示例10: execute_sql
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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 #
##############
示例11: fetch_notifications
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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)
示例12: wrap_insert
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
def wrap_insert(site, sid, title, link, pubdate, t):
try:
cursor.execute(insert_sql.format(sid=sid, site=site, title=title, link=link, pubDate=pubdate))
except pymysql.Error:
pass
else:
print("Site: {}, ID: {}, Cost: {:.5f} s, "
"pubDate: {}, Title: {}".format(site, sid, time.time() - t, pubdate, title))
示例13: exec
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
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()
示例14: _close_conn
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
def _close_conn(self):
from pymysql.err import Error
try:
self.conn.close()
except Error:
pass
示例15: test_read_procedure
# 需要導入模塊: import pymysql [as 別名]
# 或者: from pymysql import Error [as 別名]
def test_read_procedure(self):
import pymysql
# see GH7324. Although it is more an api test, it is added to the
# mysql tests as sqlite does not have stored procedures
df = DataFrame({'a': [1, 2, 3], 'b': [0.1, 0.2, 0.3]})
df.to_sql('test_procedure', self.conn, index=False)
proc = """DROP PROCEDURE IF EXISTS get_testdb;
CREATE PROCEDURE get_testdb ()
BEGIN
SELECT * FROM test_procedure;
END"""
connection = self.conn.connect()
trans = connection.begin()
try:
r1 = connection.execute(proc) # noqa
trans.commit()
except pymysql.Error:
trans.rollback()
raise
res1 = sql.read_sql_query("CALL get_testdb();", self.conn)
tm.assert_frame_equal(df, res1)
# test delegation to read_sql_query
res2 = sql.read_sql("CALL get_testdb();", self.conn)
tm.assert_frame_equal(df, res2)