def __init__(self, host, port, user, password, database): self.pool = Pool(host=host, port=port, user=user, password=password, db=database) self.pool.init()
def __init__(self): self.logger = logging.getLogger(__name__) self.__cnxPool = Pool(host='localhost', port=3306, user='******', password='******', db='pyqt_erp_proj') self.__cnxPool.init()
def __init__(self): self.pool = Pool(host="localhost", user="******", password="******", db="discordb", port=3307, autocommit=True) self.pool.init()
def __init__(self): with open("password.txt", "r") as f: password = f.read().strip("\n") self.pool = Pool(host="localhost", user="******", password=password, db="discordb", port=3306, autocommit=True) self.pool.init()
def connect_mysql(): # Connecting MySQL with connection pool pool = Pool(host=env_config.db_host, port=int(env_config.db_port), user=env_config.db_username, password=env_config.db_password, db=env_config.db_name) pool.init() global connection connection = pool.get_conn()
def __init__(self, config): if self.INSTANCE is not None: raise ValueError("An instantiation already exists!") else: self.__cnxPool = Pool(host=config.db_host, port=config.db_port, user=config.db_user, password=config.db_password, db=config.db_name) self.__cnxPool.init()
def _init_pool(self): self.pool = Pool(host=self.host, port=self.port, user=self.user, password=self.password, db=self.dbname, charset=config.DATABASE_CHARSET, cursorclass=self.cursor_class, autocommit=self.autocommit, max_size=config.DATABASE_CONNECTION_POOL_SIZE)
class MySQLTESTDB(MySQLDB): def __init__(self): self.pool = Pool(host="localhost", user="******", password="******", db="discordb", port=3307, autocommit=True) self.pool.init() def rollback_transaction(self): self.db.rollback()
def __init__(self, config): mysql_section = config['mysql'] database = mysql_section['database'] host = mysql_section['host'] password = mysql_section['password'] user = mysql_section['user'] _pool = Pool( cursorclass=pymysql.cursors.DictCursor, database=database, host=host, password=password, user=user, ) _pool.init() self._pool = _pool
class DbController: pool = Pool(**translationFile_Dict) pool.init() def __init__(self, host, user, password, db, charset): self.dbconn = pymysql.connect(host=host, user=user, password=password, db=db, charset=charset) self.dbcursor = self.dbconn.cursor(pymysql.cursors.DictCursor) def insert_db(self, tableName, values): print(queryString) self.dbcursor.execute("INSERT INTO " + tableName + " VALUES " + str(values)) self.dbconn.commit() pass def delete_db(self, queryString): self.dbcursor.execute(queryString) self.dbconn.commit() pass def select_db(self, queryString): print(queryString) self.dbcursor.execute(queryString) result = self.dbcursor.fetchone() #fetchall, fetchone return result pass def update_db(self): pass
class DatabasePool(SingleTonInstance): def __init__(self): self.logger = logging.getLogger(__name__) self.__cnxPool = Pool(host='localhost', port=3306, user='******', password='******', db='pyqt_erp_proj') self.__cnxPool.init() def __enter__(self): self.logger.debug('__enter__') self.conn = self.__cnxPool.get_conn() return self.conn def __exit__(self, exc_type, exc_val, exc_tb): self.logger.debug('__enter__') self.__cnxPool.release(self.conn)
class DatabasePool(object): INSTANCE = None def __init__(self, config): if self.INSTANCE is not None: raise ValueError("An instantiation already exists!") else: self.__cnxPool = Pool(host=config.db_host, port=config.db_port, user=config.db_user, password=config.db_password, db=config.db_name) self.__cnxPool.init() @classmethod def get_instance(cls, config): if cls.INSTANCE is None: cls.INSTANCE = DatabasePool(config) return cls.INSTANCE def get_connection(self): return self.__cnxPool.get_conn() @classmethod def pool_close(cls): cls.INSTANCE = None def __enter__(self): self.conn = self.__cnxPool.get_conn() return self.conn def __exit__(self, exc_type, exc_val, exc_tb): self.__cnxPool.release(self.conn)
def create_conn(): try: ##https://github.com/egmkang/PyMySQLPool ##https://pypi.org/project/pymysql-pooling/ # cursor = pymysql.cursors.DictCursor pool = Pool(host=mysql_host, \ port=int(mysql_port), \ user=mysql_user, \ password=mysql_password, \ database=mysql_db, \ charset='utf8') pool.init() connection = pool.get_conn() cursor = connection.cursor() cursor.execute(fn_sql) result = cursor.fetchall() return result except pymysql.err.OperationalError as err: print('create_conn ', err) os._exit(1) except: print('MySQL Error create_conn') os._exit(1)
def executeSQL(self, sql): global pool try: self.curs = self.conn.cursor() self.curs.execute(sql) except pymysql.err.OperationalError as e: pool = Pool(host=ServerInfoSetting.DB_HOST, port=ServerInfoSetting.DB_PORT, user=ServerInfoSetting.DB_USER, password=ServerInfoSetting.DB_PASSWORD, db=ServerInfoSetting.DB_NAME, autocommit=ServerInfoSetting.DB_AUTO_COMMIT, max_size=ServerInfoSetting.DB_MAX_POOL_SIZE, timeout=ServerInfoSetting.DB_TIMEOUT, min_size=1) except Exception as e: LogCat.log(ErrLevel.unknown, traceback.format_exc()) raise e
import pymysql from pymysqlpool.pool import Pool from serverConstants.ServerSettings import ServerInfoSetting from importLib.ErrorLib import * pool = Pool(host=ServerInfoSetting.DB_HOST, port=ServerInfoSetting.DB_PORT, user=ServerInfoSetting.DB_USER, password=ServerInfoSetting.DB_PASSWORD, db=ServerInfoSetting.DB_NAME, autocommit=ServerInfoSetting.DB_AUTO_COMMIT, max_size=ServerInfoSetting.DB_MAX_POOL_SIZE, timeout=ServerInfoSetting.DB_TIMEOUT, min_size=1) class SQLConnection: @staticmethod def getConnection(): global pool try: if ServerInfoSetting.SHOW_POOL_LOG: print('POOL SIZE ' + str(pool.get_pool_size())) # TODO: POOL SIZE return pool.get_conn() except Exception as e: LogCat.log(ErrLevel.unknown, traceback.format_exc()) class MySQLPool: def __init__(self, conn):
class Database: def __init__(self, pooling=True, db_host=config.DATABASE_HOST, db_port=config.DATABASE_PORT, db_user=config.DATABASE_USER, db_password=config.DATABASE_PASSWORD, autocommit=False, db_name=config.DATABASE_NAME, cursor_class=pymysql.cursors.Cursor): self.last_n = None self.pool = None self.conn = None self.host = db_host self.port = db_port self.user = db_user self.password = db_password self.dbname = db_name self.pooling = pooling self.autocommit = autocommit self.cursor_class = cursor_class if pooling: self._init_pool() else: self._init_connection() def __del__(self): if not self.pooling and self.conn: self.conn.close() def _init_connection(self): self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, db=self.dbname, charset=config.DATABASE_CHARSET, cursorclass=self.cursor_class, autocommit=self.autocommit) def _init_pool(self): self.pool = Pool(host=self.host, port=self.port, user=self.user, password=self.password, db=self.dbname, charset=config.DATABASE_CHARSET, cursorclass=self.cursor_class, autocommit=self.autocommit, max_size=config.DATABASE_CONNECTION_POOL_SIZE) @contextmanager def connection(self, ping=False, do_not_begin=False, begin=False): if not self.pooling: if ping: self.conn.ping(reconnect=True) if begin or not do_not_begin and not self.autocommit: self.conn.begin() yield self.conn if begin or not do_not_begin and not self.autocommit: self.conn.commit() else: connection = self.pool.get_conn() try: self.conn = connection if ping: self.conn.ping(reconnect=True) if begin or not do_not_begin and not self.autocommit: connection.begin() yield connection if begin or not do_not_begin and not self.autocommit: connection.commit() self.conn = None finally: self.pool.release(connection) def _query(self, sql, args, query_func): with self.connection(ping=True) as connection: try: return query_func(connection, sql, args) except (InternalError, OperationalError) as e: code, _ = e.args connection.ping(reconnect=True) if code == 1927 or code == 1046: # Connection was killed or no database selected connection.select_db(self.dbname) return query_func(connection, sql, args) def query(self, sql, args=None): self.last_n, response = self._query(sql, args, query) return response def query_many(self, sql, args): self.last_n, response = self._query(sql, args, query_many) return response def create(self, if_not_exists=True, db_name=None): db_name = db_name or self.dbname if_clause = 'IF NOT EXISTS' if if_not_exists else '' return self.query(f'CREATE DATABASE {if_clause} {db_name};') def use(self, db_name): if not self.pooling: self.conn.select_db(db_name) self.dbname = db_name else: # the following line is there to raise an exception when user is denied access self.pool.get_conn().select_db(db_name) self.pool.destroy() self.dbname = db_name self._init_pool() def drop(self, if_exists=True, db_name=None): drop_db = db_name or self.dbname if_clause = 'IF EXISTS' if if_exists else '' return self.query(f'DROP DATABASE {if_clause} {drop_db};') def reset(self, if_exists=True, db_name=None): """ALL DATA IS LOST: Recreate database {db_name} or {self.dbname} with no tables. """ drop_db = db_name or self.dbname self.drop(if_exists=if_exists, db_name=drop_db) self.create(drop_db) if db_name == self.dbname: self.use(self.dbname) def databases(self): return [record[0] for record in self.query('SHOW DATABASES;')] def tables(self, db_name=None): db_name = db_name if db_name else self.dbname db_name = db_name if db_name else config.DATABASE_NAME if not db_name: raise ValueError( 'No database given (not even dbname was set in the config file).' ) return [ record[0] for record in self.query( f'SHOW TABLES FROM {config.DATABASE_NAME};') ] def setup(self, db_name=None): db_name = db_name if db_name else self.dbname db_name = db_name if db_name else config.DATABASE_NAME if not db_name: raise ValueError( 'No database given (not even dbname was set in the config file).' ) databases = self.databases() if db_name not in databases: self.create(if_not_exists=False, db_name=db_name)
def create_conn_pool( db_host, db_user, db_passwd, db_name ): pool = Pool( host=db_host, user=db_user, password=db_passwd, db=db_name ) return pool
# pip install pymysql-pooling # Note: you can also add any parameters relates to `pymysql.connections.Connection` object from pymysqlpool.pool import Pool pool = Pool(host='localhost', port=3306, user='******', password='******', db='pyqt_erp') pool.init() connection = pool.get_conn() cur = connection.cursor() cur.execute('select title_no, title_name from title where title_no=%s', args=("1", )) print(cur.fetchone()) pool.release(connection)
from enviroment import * from pymysqlpool.pool import Pool connection_pool = Pool( host=MYSQL_HOST, port=MYSQL_PORT, db=MYSQL_SCHEMA, user=MYSQL_USER, password=MYSQL_PASSWORD, autocommit=True, ping_check=True )
import logging import pymysql from pymysqlpool.pool import Pool pool = Pool(host="maria.ryannull.com", port=3306, user="******", password="******", db="otc", min_size=1, max_size=2) pool.init() def just_end_it_all(): pool.destroy() def set_data(thing, value): connection = pool.get_conn() cursor = connection.cursor() try: connection.begin() cursor.execute('UPDATE databits SET val=%s WHERE nam=%s', (value, thing)) if thing == "og" and value == "1" and get_data('og') == '0': cursor.execute('REPLACE INTO databits (nam,val) VALUES(%s,%s)', ( "touchdown_vs",
from pymysqlpool.pool import Pool from secrets import MARIADB_USER, MARIADB_DB, MARIADB_PASSWORD, MARIADB_HOST pool = Pool(host=MARIADB_HOST, user=MARIADB_USER, password=MARIADB_PASSWORD, db=MARIADB_DB, autocommit=True) pool.init() connection = pool.get_conn() cur = connection.cursor() cur.execute('SELECT * FROM web2020_events WHERE location IS NULL') print(cur.fetchone()) pool.release(connection) print('Finished')
print('[INFO] INSERT DATABASE: SUCCESS') print('[INFO] %s, %s, %s' % (data[0], data[1], time.ctime(timestamp))) except: print('[ERROR] INSERT DATABASE: FAIL') finally: pool.release(connection) if __name__ == '__main__': pool = Pool(host=DB_HOST, port=DB_PORT, user=DB_USERNAME, password=DB_PASSWORD, db=DB_SCHEMA, cursorclass=pymysql.cursors.DictCursor, autocommit=True, min_size=1, max_size=10) pool.init() Connected = False client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD) client.connect(MQTT_HOST) client.loop_start()
for w in sentence.split(): if w in lemma_map and len(lemma_map[w]["sentences"]) < 5000: print(sentence) lemma_map[w]["sentences"].append(sentence) if __name__ == '__main__': user = '******' pw = 'root' host = "localhost" db = "demo_dict" url = 'https://www.merriam-webster.com/dictionary/' pool = Pool(user=user, password=pw, host=host, db=db, autocommit=True, cursorclass=pymysql.cursors.DictCursor) pool.init() conn = pool.get_conn() with conn.cursor() as cursor: cursor.execute( "select distinct dl.lemma from dictionary_lemma dl inner join dictionary_lemma_examples dle on dle.lemma_id = dl.id" ) already_examples = cursor.fetchall() for lemma in Lemma.objects.all(): lemma_map[lemma.lemma] = { "pos_freq": {}, "sentences": [], "collocations": [],
import vk_botting from pymysqlpool.pool import Pool # Для работы с сервером и БД import pymysql import datetime bot = vk_botting.Bot(vk_botting.when_mentioned_or_pm(), case_insensitive=True) config = { 'host': cred.host, 'user': cred.user, 'password': cred.password, 'db': cred.db, 'autocommit': True, 'charset': cred.charset, 'cursorclass': pymysql.cursors.DictCursor } try: sqlpool = Pool(**config) sqlpool.init() except Exception as exc: print(exc) def sex_transform(sex): if int(sex) == 1: return 'м' else: return 'ж' def mainmenu(): keyboard = vk_botting.Keyboard() keyboard.add_button('Искать', vk_botting.KeyboardColor.PRIMARY)
class mySql: def __init__(self, host, port, user, password, database): self.pool = Pool(host=host, port=port, user=user, password=password, db=database) self.pool.init() def fetchone(self, sql, parama): newparama = [] news = [] for each in parama: if isinstance(each, list): newparama.extend(each) news.append(','.join(['%s'] * len(each))) else: newparama.append(each) news.append('%s') # for index,data in enumerate(news): # sql = sql.replace('%s', data, 1) sql = sql % tuple(news) connection = self.pool.get_conn() cur = connection.cursor() cur.execute(sql, args=tuple(newparama)) ret = cur.fetchone() self.pool.release(connection) return def fetchall(self, sql, parama): newparama = [] news = [] for each in parama: if isinstance(each, list): newparama.extend(each) news.append(','.join(['%s'] * len(each))) else: newparama.append(each) news.append('%s') # for index,data in enumerate(news): # sql = sql.replace('%s', data, 1) sql = sql % tuple(news) connection = self.pool.get_conn() cur = connection.cursor() cur.execute(sql, args=tuple(newparama)) ret = cur.fetchall() self.pool.release(connection) return ret def update(self, sql, parama): newparama = [] news = [] for each in parama: if isinstance(each, list): newparama.extend(each) news.append(','.join(['%s'] * len(each))) else: newparama.append(each) news.append('%s') sql = sql % tuple(news) print(sql) connection = self.pool.get_conn() cur = connection.cursor() cur.execute(sql, args=tuple(newparama)) connection.commit() self.pool.release(connection) def hp(): print('修改') print("sql = mySql('127.0.0.1', 3306, 'root', 'juiuijiju', 'mysql')") print("cmd = 'update student set name=%s where id=%s'") print("sql.update(cmd, ['修改', '3'])") print() print("插入") print("cmd = 'insert into student values(%s)'") print("sql.update(cmd, [['3', '三力士']])") print() print("查询") print("cmd = 'select * from student where id in (%s)'") print("sql.fetchall(cmd, [['1', '2']])") print("sql.fetchone(cmd, [['1', '2']])") print() print("删除") print("cmd = 'delete from student where id=%s'") print("sql.update(cmd, ['3',])")
from pymysqlpool.pool import Pool from logcat.Log import LogCat pool = Pool(host='220.88.163.147', port=3306, user='******', password='******', db='MESSENGER', autocommit=True) class MySQLPool: @staticmethod def startSQLPool(): pool.init() @staticmethod def getConnection(): return pool.get_conn() @staticmethod def release(connection): pool.release(connection)
return result @classmethod def delete_db(cls, querystring): connection = cls.pool.get_conn() cursor = connection.cursor() result = cursor.execute(querystring) cls.pool.release(connection) return result @classmethod def update_db(cls, querystring): pass pool = Pool(**_db_info) pool.init() connection = pool.get_conn() cur = connection.cursor() #result = cur.execute("insert into user values('a2da','adad','adadad')") #print(pool.get_pool_size()) cur.execute("select * from session;") print(cur.fetchone()) #print(result, type(result)) pool.release(connection)
from flask import Flask, render_template, request, jsonify from pymysqlpool.pool import Pool from recaptcha import verify_recaptcha, PUB import string import random app = Flask(__name__) BASE_DB = "cloudtable" USERNAME = os.getenv("DB_USER") PASSWORD = os.getenv("DB_PASSWORD") HOST = "35.193.26.163" pool = Pool(host=HOST, user=USERNAME, password=PASSWORD, db="mysql", autocommit=True) pool.init() SCHEMA_TYPES = {1: "INT", 2: "CHAR(255)", 3: "BOOL"} def random_string(): letters = string.ascii_lowercase return ''.join(random.choice(letters) for _ in range(14)) def random_password(): letters = string.ascii_lowercase + string.ascii_uppercase + string.digits return ''.join(random.choice(letters) for _ in range(31))