install
pip install mysql-connector-python-rf 报错
从https://dev.mysql.com/downloads/connector/python/ 下载
[root@mhc 下载]# rpm -ivh mysql-connector-python-2.1.6-1.el7.x86_64.rpm
准备中... ################################# [100%]
正在升级/安装...
1:mysql-connector-python-2.1.6-1.el################################# [100%]
test
client.py:
import os
import re
import subprocess
from collections import OrderedDict
import string
import socket
import logging as log
import mysql.connector as mysqlconn
import time
import pwd
from mysql.connector import Error as MySQLError
class Error(Exception):pass
class MySQL(object):
"""
MySQL represents the connection to and configuration of the MySQL
process and its clients.
"""
def __init__(self, db=None,user="test",password="test.123",root_password="root.123",repl_user="repluser",repl_password="repl.123"):
self.mysql_db = db
self.mysql_user = user
self.mysql_password = password
self.mysql_root_password = root_password
self.mysql_random_root_password = False
self.mysql_onetime_password = None
self.repl_user = repl_user
self.repl_password = repl_password
self.datadir = '/var/lib/mysql'
self.pool_size = None
# state
self.ip = "127.0.0.1"
self._conn = None
self._query_buffer = OrderedDict()
def render(self, src='/etc/my.cnf.tmpl', dest='/etc/my.cnf'):
"""
Writes-out config files, even if we've previously initialized the DB,
so that we can account for changed hostnames, resized containers, etc.
"""
pool_size = self._get_innodb_buffer_pool_size()
with open(src, 'r') as f:
template = string.Template(f.read())
rendered = template.substitute(buffer=pool_size,
server_id=self.server_id,
hostname=self.ip)
with open(dest, 'w') as f:
f.write(rendered)
@property
def server_id(self):
""" replace server-id with ID derived from hostname """
_hostname = socket.gethostname()
return int(str(_hostname)[:4], 16)
def _get_innodb_buffer_pool_size(self):
"""
replace innodb_buffer_pool_size value from environment
or use a sensible default (70% of available physical memory)
"""
if not self.pool_size:
with open('/proc/meminfo', 'r') as memInfoFile:
memInfo = memInfoFile.read()
base = re.search(r'^MemTotal: *(\d+)', memInfo).group(1)
self.pool_size = int((int(base) / 1024) * 0.7)
return self.pool_size
@property
def conn(self):
"""
Convenience method for setting up a cached connection
with the replication manager user.
"""
if self._conn:
return self._conn
ctx = dict(user=self.repl_user,
password=self.repl_password,
timeout=25) # derived from ContainerPilot config ttl
self._conn = self.wait_for_connection(**ctx)
return self._conn
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/lib/mysql/mysql.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 Error(ex)
time.sleep(1)
def add(self, stmt, params=()):
""" Adds a new SQL statement to an internal query buffer """
self._query_buffer[stmt] = params
def execute(self, sql, params=(), conn=None):
""" Execute and commit a SQL statement with parameters """
self.add(sql, params)
self._execute(conn, discard_results=True)
def execute_many(self, conn=None):
"""
Execute and commit all previously `add`ed statements
in the query buffer
"""
self._execute(conn, discard_results=True)
def query(self, sql, params=(), conn=None):
""" Execute a SQL query with params and return results. """
self.add(sql, params)
return self._execute(conn=conn)
def _execute(self, conn=None, discard_results=False):
"""
Execute and commit all composed statements and flushes the buffer
"""
try:
if not conn:
conn = self.conn
except (Error, MySQLError):
raise # unrecoverable
try:
cur = conn.cursor(dictionary=True, buffered=True)
for stmt, params in self._query_buffer.items():
log.debug('%s %s', stmt, params)
cur.execute(stmt, params=params)
if not discard_results:
return cur.fetchall()