def slavestatus(host, port, username, password, query, perf_data, warning, critical): try: warning = warning or 120 critical = critical or 180 db = _mysql.connection(host=host, port=port, user=username, passwd=password) db.query("show slave status") result = db.store_result() status = result.fetch_row(how=2)[0] if query in status: param = status[query] if re.match(r"^\d+$", param): param = float(param) else: print "WARNING - there are on status %s in slave" % query exit(1) message = "%s is %.2f" % (query, param) message += performance_data(perf_data, [(param, query, warning, critical)]) return check_levels(param, warning, critical, message) except Exception, e: print e return exit_with_general_critical(e)
def __init__(self, *args, **kwargs): """ Create a connection to the database. It is strongly recommended that you only use keyword parameters. Consult the MySQL C API documentation for more information. host string, host to connect user string, user to connect as passwd string, password to use db string, database to use port integer, TCP/IP port to connect to unix_socket string, location of unix_socket to use decoders list, SQL decoder stack encoders list, SQL encoder stack connect_timeout number of seconds to wait before the connection attempt fails. compress if set, compression is enabled named_pipe if set, a named pipe is used to connect (Windows only) init_command command which is run once the connection is created read_default_file file from which default client values are read read_default_group configuration group to use from the default file use_unicode If True, text-like columns are returned as unicode objects using the connection's character set. Otherwise, text-like columns are returned as strings. columns are returned as normal strings. Unicode objects will always be encoded to the connection's character set regardless of this setting. charset If supplied, the connection character set will be changed to this character set (MySQL-4.1 and newer). This implies use_unicode=True. sql_mode If supplied, the session SQL mode will be changed to this setting (MySQL-4.1 and newer). For more details and legal values, see the MySQL documentation. client_flag integer, flags to use or 0 (see MySQL docs or constants/CLIENTS.py) ssl dictionary or mapping, contains SSL connection parameters; see the MySQL documentation for more details (mysql_ssl_set()). If this is set, and the client does not support SSL, NotSupportedError will be raised. local_infile integer, non-zero enables LOAD LOCAL INFILE; zero disables There are a number of undocumented, non-standard methods. See the documentation for the MySQL C API for some hints on what they do. """ from MySQLdb.constants import CLIENT, FIELD_TYPE from MySQLdb.converters import default_decoders, default_encoders, default_row_formatter from MySQLdb.cursors import Cursor import _mysql kwargs2 = kwargs.copy() self.cursorclass = Cursor charset = kwargs2.pop('charset', '') self.encoders = kwargs2.pop('encoders', default_encoders) self.decoders = kwargs2.pop('decoders', default_decoders) self.row_formatter = kwargs2.pop('row_formatter', default_row_formatter) client_flag = kwargs.get('client_flag', 0) client_version = tuple( [ int(n) for n in _mysql.get_client_info().split('.')[:2] ]) if client_version >= (4, 1): client_flag |= CLIENT.MULTI_STATEMENTS if client_version >= (5, 0): client_flag |= CLIENT.MULTI_RESULTS kwargs2['client_flag'] = client_flag sql_mode = kwargs2.pop('sql_mode', None) self._db = _mysql.connection(*args, **kwargs2) self._server_version = tuple( [ int(n) for n in self._db.get_server_info().split('.')[:2] ]) if charset: self._db.set_character_set(charset) if sql_mode: self.set_sql_mode(sql_mode) self._transactional = bool(self._db.server_capabilities & CLIENT.TRANSACTIONS) if self._transactional: # PEP-249 requires autocommit to be initially off self.autocommit(False) self.messages = [] self._active_cursor = None
#!/usr/bin/python # -*- coding: utf-8 -*- import _mysql import threading import os import paths import database import re db = _mysql.connection(host=database.host, user=database.user, passwd=database.passwd, db=database.dbname) while True: pat = re.compile('index.html') try: list1 = os.listdir(paths.statusPath) list1.sort() for i in list1: if i[0] == '.': continue if pat.search(i) != None: continue data = i.split('.') db.query("UPDATE pc_submit SET SCORE = '" + data[2] + "', STATUS_ID = '" + data[3] + "', SUBMIT_LOG = '" + data[4] + "' WHERE SUBMIT_HASH ='" + data[1] + "'") os.system('rm -f ' + paths.statusPath + '*') except Exception:
import sys import _mysql as sql try: con = sql.connection("localhost", "Eclipse", "hedgefund", "Eclipse") all_tables = ['Company', 'Document', 'Employee', 'Scripts', 'Stock'] for i in sys.argv: if i in all_tables: print 'Resetting %s' % i table_del = "DELETE FROM %s;" % i con.query(table_del) if i == 'Company': con.query("ALTER TABLE Company AUTO_INCREMENT = 1;") con.query("INSERT INTO Company (ticker) VALUES (\'Dummy\');") elif i == 'Document': con.query("ALTER TABLE Document AUTO_INCREMENT = 1;") con.query("INSERT INTO Document (doc_name) VALUES (\'Dummy Doc\');") elif i == 'Employee': con.query("ALTER TABLE Employee AUTO_INCREMENT = 1;") con.query("INSERT INTO Employee (first_name, last_name) VALUES (\'Ruiqi\', \'Yu\');") elif i == 'Scripts': con.query("ALTER TABLE Scripts AUTO_INCREMENT = 1;") con.query("INSERT INTO Scripts (eid) VALUES (1);") elif i == 'Stock': con.query("ALTER TABLE Stock AUTO_INCREMENT = 1;") con.query("INSERT INTO Stock (ticker) VALUES (\'Dummy\');") except sql.Error, e: print 'DB error %d: %s' % (e.args[0], e.args[1]) sys.exit(0)
def __init__(self, *args, **kwargs): """ Create a connection to the database. It is strongly recommended that you only use keyword parameters. Consult the MySQL C API documentation for more information. host string, host to connect user string, user to connect as passwd string, password to use db string, database to use port integer, TCP/IP port to connect to unix_socket string, location of unix_socket to use conv conversion dictionary, see MySQLdb.converters connect_timeout number of seconds to wait before the connection attempt fails. compress if set, compression is enabled named_pipe if set, a named pipe is used to connect (Windows only) init_command command which is run once the connection is created read_default_file file from which default client values are read read_default_group configuration group to use from the default file cursorclass class object, used to create cursors (keyword only) use_unicode If True, text-like columns are returned as unicode objects using the connection's character set. Otherwise, text-like columns are returned as strings. columns are returned as normal strings. Unicode objects will always be encoded to the connection's character set regardless of this setting. charset If supplied, the connection character set will be changed to this character set (MySQL-4.1 and newer). This implies use_unicode=True. sql_mode If supplied, the session SQL mode will be changed to this setting (MySQL-4.1 and newer). For more details and legal values, see the MySQL documentation. client_flag integer, flags to use or 0 (see MySQL docs or constants/CLIENTS.py) ssl dictionary or mapping, contains SSL connection parameters; see the MySQL documentation for more details (mysql_ssl_set()). If this is set, and the client does not support SSL, NotSupportedError will be raised. local_infile integer, non-zero enables LOAD LOCAL INFILE; zero disables There are a number of undocumented, non-standard methods. See the documentation for the MySQL C API for some hints on what they do. """ from MySQLdb.constants import CLIENT, FIELD_TYPE from MySQLdb.converters import conversions from MySQLdb.cursors import Cursor import _mysql from weakref import proxy kwargs2 = kwargs.copy() if 'conv' in kwargs: conv = kwargs['conv'] else: conv = conversions conv2 = {} for k, v in conv.items(): if isinstance(k, int): if isinstance(v, list): conv2[k] = v[:] else: conv2[k] = v # TODO Remove this when we can do conversions in non-C space. kwargs2['conv'] = conv2 self.cursorclass = kwargs2.pop('cursorclass', Cursor) charset = kwargs2.pop('charset', '') if charset: use_unicode = True else: use_unicode = False use_unicode = kwargs2.pop('use_unicode', use_unicode) sql_mode = kwargs2.pop('sql_mode', '') client_flag = kwargs.get('client_flag', 0) client_version = tuple( [ int(n) for n in _mysql.get_client_info().split('.')[:2] ]) if client_version >= (4, 1): client_flag |= CLIENT.MULTI_STATEMENTS if client_version >= (5, 0): client_flag |= CLIENT.MULTI_RESULTS kwargs2['client_flag'] = client_flag self._db = _mysql.connection(*args, **kwargs2) self.encoders = dict( [ (k, v) for k, v in conv.items() if type(k) is not int ]) self._server_version = tuple( [ int(n) for n in self._db.get_server_info().split('.')[:2] ]) db = proxy(self) def _get_string_literal(): def string_literal(obj, dummy=None): return self._db.string_literal(obj) return string_literal def _get_unicode_literal(): def unicode_literal(u, dummy=None): return self.literal(u.encode(unicode_literal.charset)) return unicode_literal def _get_string_decoder(): def string_decoder(s): return s.decode(string_decoder.charset) return string_decoder string_literal = _get_string_literal() self.unicode_literal = unicode_literal = _get_unicode_literal() self.string_decoder = string_decoder = _get_string_decoder() if not charset: charset = self._db.character_set_name() self._db.set_character_set(charset) if sql_mode: self.set_sql_mode(sql_mode) #if use_unicode: #self._db.converter[FIELD_TYPE.STRING].append((None, string_decoder)) #self._db.converter[FIELD_TYPE.VAR_STRING].append((None, string_decoder)) #self._db.converter[FIELD_TYPE.VARCHAR].append((None, string_decoder)) #self._db.converter[FIELD_TYPE.BLOB].append((None, string_decoder)) self.encoders[str] = string_literal self.encoders[unicode] = unicode_literal string_decoder.charset = charset unicode_literal.charset = charset self._transactional = self._db.server_capabilities & CLIENT.TRANSACTIONS if self._transactional: # PEP-249 requires autocommit to be initially off self.autocommit(False) self.messages = []
def __init__(self, host, user, passwd, db) : self.dbh = MySQLdb.connection(host, user, passwd, db)
def __init__(self, **kwargs): # Argument remapping for one,two in self.KWMAP.items(): if one in kwargs: kwargs[two] = kwargs[one] del(kwargs[one]) # Create the connection self.CONN = _mysql.connection(**kwargs) # Establish MySQL to Python conversions self.CONN.converter = { FIELD_TYPE.DECIMAL: Decimal, FIELD_TYPE.TINY: int, FIELD_TYPE.SHORT: int, FIELD_TYPE.LONG: int, FIELD_TYPE.FLOAT: float, FIELD_TYPE.DOUBLE: float, FIELD_TYPE.NULL: lambda value: None, FIELD_TYPE.LONGLONG: int, FIELD_TYPE.INT24: int, FIELD_TYPE.BIT: int, FIELD_TYPE.NEWDECIMAL: Decimal, } QSL = self.CONN.string_literal # Establish Python to SQL conversions # ie. {{conv:varname}} self.CONV = { 'bool' : lambda v: "1" if v else "0", 'bool/null' : lambda v: 'NULL' if v == None else ("1" if v else "0"), 'int' : lambda v: str(int(v)), 'int/list' : lambda v: str.join(', ', [str(int(s)) for s in v]) if len(v) else 'NULL', 'int/null' : lambda v: 'NULL' if v == None else str(int(v)), 'float' : lambda v: str(float(v)), 'float/list' : lambda v: str.join(', ', [str(float(s)) for s in v]) if len(v) else 'NULL', 'float/null' : lambda v: 'NULL' if v == None else str(float(v)), 'string' : lambda v: self.CONN.string_literal(str(v)), 'string/list' : lambda v: str.join(', ', [QSL(str(s)) for s in v]) if len(v) else 'NULL', 'string/null' : lambda v: 'NULL' if v == None else QSL(str(v)), 'decimal' : lambda v: str(Decimal(v)), 'decimal/list' : lambda v: str.join(', ', [str(Decimal(s)) for s in v]) if len(v) else 'NULL', 'decimal/null' : lambda v: 'NULL' if v == None else str(Decimal(v)), 'sql' : lambda v: str(v), } # Will hold the last 20 queries self.QueryHist = [] # Will hold the query count self.QueryCount = 0 # Stack of transaction objects self.TransactionStack = []