本文整理汇总了Python中mysql.connector.connect方法的典型用法代码示例。如果您正苦于以下问题:Python connector.connect方法的具体用法?Python connector.connect怎么用?Python connector.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mysql.connector
的用法示例。
在下文中一共展示了connector.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getTotalSoftwares
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def getTotalSoftwares():
response.set_header("Access-Control-Allow-Origin", "*")
db = mariadb.connect(user=Settings.MONITOR_DB['user'], password=Settings.MONITOR_DB['password'], database=Settings.MONITOR_DB['database'])
softwares = collections.OrderedDict()
maxDays = request.GET.get('maxDays', '31').strip()
maxDays = int(maxDays) - 1
query = """SELECT name, SUM(hits) AS total, MAX(dateStats) AS maxDate
FROM softwares
GROUP BY name
HAVING maxDate >= DATE_SUB(NOW(), INTERVAL %s DAY)
ORDER BY total DESC"""
results = db.cursor()
results.execute(query, (maxDays, ))
for row in results:
softwares[row[0].encode('utf8')] = str(row[1])
db.close()
return simplejson.dumps(softwares)
示例2: getTotalSchemas
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def getTotalSchemas():
response.set_header("Access-Control-Allow-Origin", "*")
db = mariadb.connect(user=Settings.MONITOR_DB['user'], password=Settings.MONITOR_DB['password'], database=Settings.MONITOR_DB['database'])
schemas = collections.OrderedDict()
query = """SELECT `name`, SUM(`hits`) AS `total`
FROM `schemas`
GROUP BY `name`
ORDER BY `total` DESC"""
results = db.cursor()
results.execute(query)
for row in results:
schemas[str(row[0])] = row[1]
db.close()
return simplejson.dumps(schemas)
示例3: __init__
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def __init__(self, user, password, database=None, verbose=LOG_OFF):
# passwd = input("Password > ")
# passwd = password
self._v = verbose
if database is not None:
self.database = database
try:
self.conn = maria.connect(user=user, password=password, database=self.database)
except maria.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
try:
self.conn = maria.connect(user=user, password=password)
except maria.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
else:
print(err)
示例4: _connect
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def _connect(self):
if self.quiet is False:
kodi.log("Connecting to " + self.db_file)
try:
from sqlite3 import dbapi2 as database
if self.quiet is False:
kodi.log("%s loading sqlite3 as DB engine" % kodi.get_name())
except:
from pysqlite2 import dbapi2 as database
if self.quiet is False:
kodi.log("%s loading pysqlite2 as DB engine" % kodi.get_name())
if self.quiet is False:
kodi.log("Connecting to SQLite on: " + self.db_file)
directory = kodi.vfs.dirname(self.db_file)
if not kodi.vfs.exists(directory): kodi.vfs.mkdir(directory)
self.DBH = database.connect(self.db_file, check_same_thread=False)
try:
self.DBC = self.DBH.cursor()
self.__connected = True
except Exception as e:
self.handel_error(DatabaseException("SQLite Database Error: %s" % e))
kodi.log("SQLite Database Error: %s" % e)
示例5: connect
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def connect(self):
import mysql.connector as database
self.dbh = database.connect(**self.dsn)
self.dbc = self.dbh.cursor()
try:
self.query("SELECT db_version FROM version")
except:
if self.custom_tables:
statements = self.create_statements + self.custom_tables + ["COMMIT;", "SET autocommit=1;"]
else:
statements = self.create_statements
for SQL in statements:
self.execute(SQL)
self.commit()
self.connected = True
示例6: wait_for_connection
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def wait_for_connection(self, user='root', password=None, database=None,
timeout=10):
"""
Polls mysqld socket until we get a connection or the timeout
expires (raise WaitTimeoutError). Defaults to root empty/password.
"""
while timeout > 0:
try:
sock = '/var/run/mysqld/mysqld.sock'
return mysqlconn.connect(unix_socket=sock,
user=user,
password=password,
database=database,
charset='utf8',
connection_timeout=timeout)
except MySQLError as ex:
timeout = timeout - 1
if timeout == 0:
raise WaitTimeoutError(ex)
time.sleep(1)
示例7: database_connection_mysql
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def database_connection_mysql(host, port, db, user, password):
if MySQLdb:
# TODO: should provide support for MySQL 'option-files' too.
if host is None:
host = 'localhost'
if port is None:
port = 3306
if user is None:
user = getpass.getuser()
if password:
try:
return MySQLdb.connect(host=host, port=port, db=db,
user=user, password=password)
except:
# some versions of the MySQL driver use different names
return MySQLdb.connect(host=host, port=port, db=db,
username=user, passwd=password)
else:
return MySQLdb.connect(host=host, port=port, db=db, user=user)
else:
print('MySQL driver not available', file=sys.stderr)
示例8: main
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def main():
"""The main program"""
args = parse_args()
items = []
now = str(int(time()))
cnx = connect(
user=args.user,
password=args.password,
host=args.host,
db=args.dbname,
unix_socket=args.unix_socket,
)
cur = cnx.cursor()
for query in args.queries:
cur.execute(query)
if not cur.rowcount:
raise Exception('No result')
rows = [dict(zip(cur.column_names, r)) for r in cur.fetchall()]
if args.key_column:
items.extend(get_row_data(rows, args.key_column))
else:
items.extend(get_column_data(rows))
for key, value in items:
print(args.prefix + '.' + str(key), value, now)
cur.close()
cnx.close()
示例9: connect
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def connect(self):
try:
self._connection = mysql.connect(**self.settings)
except mysql.Error as e:
msg = 'Failure in connecting to database. Error: {0}'.format(e)
raise DatabaseError(msg)
示例10: __setstate__
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def __setstate__(self, state):
self.__dict__.update(state)
if isinstance(self._connection, str):
self.connect()
示例11: getSoftwares
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def getSoftwares():
response.set_header("Access-Control-Allow-Origin", "*")
db = mariadb.connect(user=Settings.MONITOR_DB['user'], password=Settings.MONITOR_DB['password'], database=Settings.MONITOR_DB['database'])
softwares = collections.OrderedDict()
dateStart = request.GET.get('dateStart', str(date('%Y-%m-%d'))).strip()
dateEnd = request.GET.get('dateEnd', str(date('%Y-%m-%d'))).strip()
query = """SELECT *
FROM `softwares`
WHERE `dateStats` BETWEEN %s AND %s
ORDER BY `hits` DESC, `dateStats` ASC"""
results = db.cursor()
results.execute(query, (dateStart, dateEnd))
for row in results:
currentDate = row[2].strftime('%Y-%m-%d')
if not currentDate in softwares.keys():
softwares[currentDate] = collections.OrderedDict()
softwares[currentDate][str(row[0])] = str(row[1])
db.close()
return simplejson.dumps(softwares)
示例12: getSchemas
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def getSchemas():
response.set_header("Access-Control-Allow-Origin", "*")
db = mariadb.connect(user=Settings.MONITOR_DB['user'], password=Settings.MONITOR_DB['password'], database=Settings.MONITOR_DB['database'])
#db.text_factory = lambda x: unicode(x, "utf-8", "ignore")
schemas = collections.OrderedDict()
dateStart = request.GET.get('dateStart', str(date('%Y-%m-%d'))).strip()
dateEnd = request.GET.get('dateEnd', str(date('%Y-%m-%d'))).strip()
query = """SELECT *
FROM `schemas`
WHERE `dateStats` BETWEEN %s AND %s
ORDER BY `hits` DESC, `dateStats` ASC"""
results = db.cursor()
results.execute(query, (dateStart, dateEnd))
for row in results:
currentDate = row[2].strftime('%Y-%m-%d')
if not currentDate in schemas.keys():
schemas[currentDate] = collections.OrderedDict()
schemas[currentDate][str(row[0])] = str(row[1])
db.close()
return simplejson.dumps(schemas)
示例13: __init__
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def __init__(self,user=mysql_user,password=mysql_password,host=mysql_host,port=mysql_port,db='mysql'):
try:
self.__user = user
self.__password = password
self.__host = host
self.__port = port
self.__db = db
self.cnx = mysql.connect(user=self.__user,password=self.__password,host=self.__host,port=self.__port,db=self.__db)
self.cur = self.cnx.cursor(buffered=True)
except Exception as e:
logging.error(e)
示例14: bruter
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def bruter(user, passwd, ip, flag=False):
try:
con = mysql.connect(user=user, password=passwd, host=ip)
flag = True
except:
pass
return flag
示例15: __init__
# 需要导入模块: from mysql import connector [as 别名]
# 或者: from mysql.connector import connect [as 别名]
def __init__(self, credentials_file=None, charset='utf8',
port=3306, engine="mysql", **kwargs):
"""
Initialise object with credentials file provided
You can choose between providing file or connection details
Available parameters:
https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
"""
if credentials_file:
with open(credentials_file, 'r') as f:
self.settings = json.load(f)
if 'port' not in self.settings:
self.settings['port'] = port
if 'charset' not in self.settings:
self.settings['charset'] = charset
# Merge with kwargs
self.settings.update(**kwargs)
self.engine = self.settings.pop('engine', engine)
# @NOTE Charset parameter not supported in PostgreSQL
if self.engine == 'postgres':
self.settings.pop('charset', None)
self._check_settings()
self.connection = None
self.cursor = None
# Establish connection and set cursor
self.connect()