本文整理汇总了Python中mysql.connector方法的典型用法代码示例。如果您正苦于以下问题:Python mysql.connector方法的具体用法?Python mysql.connector怎么用?Python mysql.connector使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mysql
的用法示例。
在下文中一共展示了mysql.connector方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_connect_args
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def create_connect_args(self, url):
opts = url.translate_connect_args(username='user')
opts.update(url.query)
util.coerce_kw_type(opts, 'buffered', bool)
util.coerce_kw_type(opts, 'raise_on_warnings', bool)
# unfortunately, MySQL/connector python refuses to release a
# cursor without reading fully, so non-buffered isn't an option
opts.setdefault('buffered', True)
# FOUND_ROWS must be set in ClientFlag to enable
# supports_sane_rowcount.
if self.dbapi is not None:
try:
from mysql.connector.constants import ClientFlag
client_flags = opts.get(
'client_flags', ClientFlag.get_default())
client_flags |= ClientFlag.FOUND_ROWS
opts['client_flags'] = client_flags
except Exception:
pass
return [[], opts]
示例2: _execute_wrapper
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def _execute_wrapper(self, method, query, args):
"""Wrapper around execute() and executemany()"""
try:
return method(query, args)
except (mysql.connector.ProgrammingError) as err:
six.reraise(utils.ProgrammingError,
utils.ProgrammingError(err.msg), sys.exc_info()[2])
except (mysql.connector.IntegrityError) as err:
six.reraise(utils.IntegrityError,
utils.IntegrityError(err.msg), sys.exc_info()[2])
except mysql.connector.OperationalError as err:
# Map some error codes to IntegrityError, since they seem to be
# misclassified and Django would prefer the more logical place.
if err.args[0] in self.codes_for_integrityerror:
six.reraise(utils.IntegrityError,
utils.IntegrityError(err.msg), sys.exc_info()[2])
else:
six.reraise(utils.DatabaseError,
utils.DatabaseError(err.msg), sys.exc_info()[2])
except mysql.connector.DatabaseError as err:
six.reraise(utils.DatabaseError,
utils.DatabaseError(err.msg), sys.exc_info()[2])
示例3: __init__
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def __init__(self, marvin_config=None, debug=None):
"""Initializes NSX class
:param marvin_config: Marvin config file
:param debug: Output debug information
"""
super(NSX, self).__init__(marvin_config=marvin_config, debug=debug)
self.nsx_zone_name = 'mct-zone'
self.nsx_user = 'admin'
self.nsx_pass = 'admin'
self.session = requests.session()
master = parse('niciraNvp[*].controllerNodes[0]').find(self.config)
self.master = socket.gethostbyname(master[0].value)
self.transport_zone_uuid = None
self.cloud_db = mysql.connector.connect(
database='cloud',
host=self.config['dbSvr']['dbSvr'],
port=self.config['dbSvr']['port'],
username=self.config['dbSvr']['user'],
password=self.config['dbSvr']['passwd']
)
示例4: _search_channels_condition
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def _search_channels_condition(self, condition, channelui):
if self.conn is None:
return
try:
if condition is None:
query = 'SELECT `id`,`channel`,0 AS `count` FROM `channel`'
qtail = ''
else:
query = 'SELECT channel.id AS `id`,`channel`,COUNT(*) AS `count` FROM `film` LEFT JOIN `channel` ON channel.id=film.channelid'
qtail = ' WHERE ' + condition + self.sql_cond_nofuture + \
self.sql_cond_minlength + ' GROUP BY channel.id'
self.logger.info('MySQL Query: {}', query + qtail)
cursor = self.conn.cursor()
cursor.execute(query + qtail)
channelui.begin()
for (channelui.channelid, channelui.channel, channelui.count) in cursor:
channelui.add()
channelui.end()
cursor.close()
except mysql.connector.Error as err:
self.logger.error('Database error: {}, {}', err.errno, err)
self.notifier.show_database_error(err)
示例5: ft_update_end
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def ft_update_end(self, delete):
"""
Finishes a local update procedure
Args:
delete(bool): if `True` all records not updated
will be deleted
"""
param = (1, ) if delete else (0, )
try:
cursor = self.conn.cursor()
cursor.callproc('ftUpdateEnd', param)
for result in cursor.stored_results():
for (del_chn, del_shw, del_mov, cnt_chn, cnt_shw, cnt_mov) in result:
cursor.close()
self.conn.commit()
return (del_chn, del_shw, del_mov, cnt_chn, cnt_shw, cnt_mov)
# should never happen
cursor.close()
self.conn.commit()
except mysql.connector.Error as err:
self.logger.error('Database error: {}, {}', err.errno, err)
self.notifier.show_database_error(err)
return (0, 0, 0, 0, 0, 0, )
示例6: _insert_channel
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def _insert_channel(self, channel):
try:
cursor = self.conn.cursor()
cursor.callproc('ftInsertChannel', (channel, ))
for result in cursor.stored_results():
for (idd, added) in result:
cursor.close()
self.conn.commit()
return (idd, added)
# should never happen
cursor.close()
self.conn.commit()
except mysql.connector.Error as err:
self.logger.error('Database error: {}, {}', err.errno, err)
self.notifier.show_database_error(err)
return (0, 0, )
示例7: _insert_show
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def _insert_show(self, channelid, show, search):
try:
cursor = self.conn.cursor()
cursor.callproc('ftInsertShow', (channelid, show, search, ))
for result in cursor.stored_results():
for (idd, added) in result:
cursor.close()
self.conn.commit()
return (idd, added)
# should never happen
cursor.close()
self.conn.commit()
except mysql.connector.Error as err:
self.logger.error('Database error: {}, {}', err.errno, err)
self.notifier.show_database_error(err)
return (0, 0, )
示例8: _instrument
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def _instrument(self, **kwargs):
"""Integrate with MySQL Connector/Python library.
https://dev.mysql.com/doc/connector-python/en/
"""
tracer_provider = kwargs.get("tracer_provider")
tracer = get_tracer(__name__, __version__, tracer_provider)
dbapi.wrap_connect(
tracer,
mysql.connector,
"connect",
self._DATABASE_COMPONENT,
self._DATABASE_TYPE,
self._CONNECTION_ATTRIBUTES,
)
示例9: create_database
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def create_database(self):
"""Create the database if it doesn't exist yet."""
output_target = self.output()
# The default behavior of MysqlTarget is to connect to a specific database, which will fail since the database
# doesn't exist yet, so we make our own connection here that is not attached to a specific database.
connection = mysql.connector.connect(
user=output_target.user,
password=output_target.password,
host=output_target.host,
port=output_target.port,
autocommit=True # These operations autocommit anyway.
)
try:
cursor = connection.cursor()
query = "CREATE DATABASE IF NOT EXISTS {db}".format(db=self.database)
log.debug(query)
cursor.execute(query)
finally:
connection.close()
示例10: get_mysql_query_results
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def get_mysql_query_results(credentials, database, query):
"""
Executes a mysql query on the provided database and returns the results.
"""
credentials_target = ExternalURL(url=credentials).output()
cred = None
with credentials_target.open('r') as credentials_file:
cred = json.load(credentials_file)
connection = mysql.connector.connect(user=cred.get('username'),
password=cred.get('password'),
host=cred.get('host'),
port=cred.get('port'),
database=database)
try:
cursor = connection.cursor()
cursor.execute(query)
results = cursor.fetchall()
finally:
connection.close()
return results
示例11: create_connect_args
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def create_connect_args(self, url):
opts = url.translate_connect_args(username='user')
opts.update(url.query)
util.coerce_kw_type(opts, 'buffered', bool)
util.coerce_kw_type(opts, 'raise_on_warnings', bool)
opts.setdefault('buffered', True)
opts.setdefault('raise_on_warnings', True)
# FOUND_ROWS must be set in ClientFlag to enable
# supports_sane_rowcount.
if self.dbapi is not None:
try:
from mysql.connector.constants import ClientFlag
client_flags = opts.get(
'client_flags', ClientFlag.get_default())
client_flags |= ClientFlag.FOUND_ROWS
opts['client_flags'] = client_flags
except:
pass
return [[], opts]
示例12: createHashDatabaseIfNotExists
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def createHashDatabaseIfNotExists(self):
log.debug('Creating hash db in database')
try:
connection = mysql.connector.connect(host=self.host,
user=self.user, port=self.port, passwd=self.password,
db=self.database)
except:
log.error("Could not connect to the SQL database")
return False
cursor = connection.cursor()
query = (' Create table if not exists trshash ( ' +
' hashid MEDIUMINT NOT NULL AUTO_INCREMENT, ' +
' hash VARCHAR(255) NOT NULL, ' +
' type VARCHAR(10) NOT NULL, ' +
' id VARCHAR(255) NOT NULL, ' +
' count INT(10) NOT NULL DEFAULT 1, ' +
' modify DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, ' +
' PRIMARY KEY (hashid))')
log.debug(query)
cursor.execute(query)
connection.commit()
cursor.close()
connection.close()
return True
示例13: getAllHash
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def getAllHash(self, type):
try:
connection = mysql.connector.connect(host=self.host,
user=self.user, port=self.port, passwd=self.password,
db=self.database)
except:
log.error("Could not connect to the SQL database")
return None
cursor = connection.cursor()
query = ('SELECT id, hash, '
'type, count, modify FROM trshash '
'HAVING type = \'' + str(type) + '\' ')
log.debug(query)
cursor.execute(query)
data = cursor.fetchall()
return data
示例14: __checkLastUpdatedColumnExists
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def __checkLastUpdatedColumnExists(self):
try:
connection = mysql.connector.connect(host=self.host,
user=self.user, port=self.port, passwd=self.password,
db=self.database)
except:
log.error("Could not connect to the SQL database")
return False
query = "SELECT count(*) FROM information_schema.columns " \
"WHERE table_name = 'raids' AND column_name = 'last_updated' AND table_schema = '{0}'".format(self.database)
cursor = connection.cursor()
cursor.execute(query)
result = int(cursor.fetchall()[0][0])
cursor.close()
connection.close()
return int(result)
# TODO: consider adding columns for last_updated timestamp to not abuse time_spawn in raids
示例15: createHashDatabaseIfNotExists
# 需要导入模块: import mysql [as 别名]
# 或者: from mysql import connector [as 别名]
def createHashDatabaseIfNotExists(self):
log.debug('Creating hash db in database')
try:
connection = mysql.connector.connect(host=self.host,
user=self.user, port=self.port, passwd=self.password,
db=self.database)
except:
log.error("Could not connect to the SQL database")
return False
cursor = connection.cursor()
query = (' Create table if not exists trshash ( ' +
' hashid MEDIUMINT NOT NULL AUTO_INCREMENT, ' +
' hash VARCHAR(255) NOT NULL, ' +
' type VARCHAR(10) NOT NULL, ' +
' id VARCHAR(255) NOT NULL, ' +
' count INT(10) NOT NULL DEFAULT 1, ' +
' modify DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, ' +
' PRIMARY KEY (hashid))')
log.debug(query)
cursor.execute(query)
connection.commit()
return True