How to use the pymysql.connect function in PyMySQL

To help you get started, we’ve selected a few PyMySQL examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github MartinThoma / hwrt / bin / create_testset_online_once.py View on Github external
def main(mysql):
    """Add testset flag to recordings in MySQL database."""
    connection = pymysql.connect(host=mysql['host'],
                                 user=mysql['user'],
                                 passwd=mysql['passwd'],
                                 db=mysql['db'],
                                 cursorclass=pymysql.cursors.DictCursor)
    cursor = connection.cursor()

    # Download all datasets
    sql = ("SELECT `id`, `formula_in_latex` FROM `wm_formula` "
           "WHERE `is_important` = 1 ORDER BY `id` ASC")
    cursor.execute(sql)
    datasets = cursor.fetchall()

    for i, data in enumerate(datasets):
        fid, formula_in_latex = data['id'], data['formula_in_latex']
        print("%i: Create testset for %s (id: %i)..." % (i,
                                                         formula_in_latex,
github welliamcao / OpsManage / utils / mysql / binlog2sql.py View on Github external
self.start_time = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        else:
            self.start_time = datetime.datetime.strptime('1980-01-01 00:00:00', "%Y-%m-%d %H:%M:%S")
        if stop_time:
            self.stop_time = datetime.datetime.strptime(stop_time, "%Y-%m-%d %H:%M:%S")
        else:
            self.stop_time = datetime.datetime.strptime('2999-12-31 00:00:00', "%Y-%m-%d %H:%M:%S")

        self.only_schemas = only_schemas if only_schemas else None
        self.only_tables = only_tables if only_tables else None
        self.no_pk, self.flashback, self.stop_never, self.back_interval = (no_pk, flashback, stop_never, back_interval)
        self.only_dml = only_dml
        self.sql_type = [t.upper() for t in sql_type] if sql_type else []

        self.binlogList = []
        self.connection = pymysql.connect(**self.conn_setting)
        with self.connection as cursor:
            cursor.execute("SHOW MASTER STATUS")
            self.eof_file, self.eof_pos = cursor.fetchone()[:2]
            cursor.execute("SHOW MASTER LOGS")
            bin_index = [row[0] for row in cursor.fetchall()]
            if self.start_file not in bin_index:
                raise ValueError('parameter error: start_file %s not in mysql server' % self.start_file)
            binlog2i = lambda x: x.split('.')[1]
            for binary in bin_index:
                if binlog2i(self.start_file) <= binlog2i(binary) <= binlog2i(self.end_file):
                    self.binlogList.append(binary)

            cursor.execute("SELECT @@server_id")
            self.server_id = cursor.fetchone()[0]
            if not self.server_id:
                raise ValueError('missing server_id in %s:%s' % (self.conn_setting['host'], self.conn_setting['port']))
github yuanfengyun / stock / stock / database / daily_price.py View on Github external
#-*- coding:utf8 -*-
import json
import pymysql
import csv
import requests
import time
from dongfang import headers

url = "http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?cb=jQuery112407468156378518487_1554296869371&type=CT&token=4f1862fc3b5e77c150a2b985b12db0fd&sty=FCOIATC&js=(%7Bdata%3A%5B(x)%5D%2CrecordsFiltered%3A(tot)%7D)&cmd=C._A&st=(ChangePercent)&sr=-1&p=1&ps=5000&_=1554296869372"

db = pymysql.connect("120.79.91.100","root","yungege_test","stock" )
cursor = db.cursor()

r = requests.get(url,headers=headers)
s = r.text
s = s[48:-23]
l = json.loads(s)
for v in l:
    values = v.split(",")
    for index,s in enumerate(values):
        if s[-1:] == "%":
            values[index] = s[:-1]
        if s=="-":
            values[index] = 0
    cur_price = values[3]
    percent = values[4]
    ttm = values[15]
github dwayn / aws-management-suite / amslib / core / manager.py View on Github external
def __init__(self, settings):
        self.settings = settings
        self.dbconn = pymysql.connect(host=self.settings.TRACKING_DB['host'],
                             port=self.settings.TRACKING_DB['port'],
                             user=self.settings.TRACKING_DB['user'],
                             password=self.settings.TRACKING_DB['pass'],
                             db=self.settings.TRACKING_DB['dbname'])
        self.db = self.dbconn.cursor()
        self.logger = self.get_logger()
        self.boto_conns = {}
        self.__subinit__()
        self._az_region_map = {}
github MartinThoma / hwrt / hwrt / segmentation / segmentation.py View on Github external
def get_segmented_raw_data(top_n=10000):
    """Fetch data from the server.

    Parameters
    ----------
    top_n : int
        Number of data sets which get fetched from the server.
    """
    cfg = utils.get_database_configuration()
    mysql = cfg["mysql_online"]
    connection = pymysql.connect(
        host=mysql["host"],
        user=mysql["user"],
        passwd=mysql["passwd"],
        db=mysql["db"],
        cursorclass=pymysql.cursors.DictCursor,
    )
    cursor = connection.cursor()
    sql = (
        "SELECT `id`, `data`, `segmentation` "
        "FROM `wm_raw_draw_data` WHERE "
        "(`segmentation` IS NOT NULL OR `accepted_formula_id` IS NOT NULL) "
        "AND `wild_point_count` = 0 "
        "AND `stroke_segmentable` = 1 "
        "ORDER BY `id` LIMIT 0, %i"
    ) % top_n
    logging.info(sql)
github RNAcentral / rnacentral-webcode / rnacentral / portal / management / commands / update_ensembl_assembly.py View on Github external
def get_ensembl_connection():
    """Connect to the public Ensembl MySQL database."""
    return pymysql.connect(
        host='ensembldb.ensembl.org',
        user='anonymous',
        port=3306,
        cursorclass=pymysql.cursors.DictCursor
    )
github Javinator9889 / telegram-yt_mp3-bot / database.py View on Github external
def cont_database(chat_id):
	# Open database connection
	db = pymysql.connect("YOUR_HOST (localhost,127.0.0.1, ...)","YOUR_USER","YOUR_PASSWORD","DATABASE_TABLE_NAME",charset='utf8')

	# prepare a cursor object using cursor() method
	c = db.cursor()
	0
	#db.set_character_set('utf8')
	c.execute('SET NAMES utf8;')
	c.execute('SET CHARACTER SET utf8;')
	c.execute('SET character_set_connection=utf8;')
	# execute SQL query using execute() method.
	#cursor.execute("SELECT VERSION()")
	c.execute("""SELECT cont_down FROM Usuario WHERE chat_id = %s """, (chat_id))
	aux = c.fetchone()
	if aux[0]==None:
		aux1=0
		print("\n\tNúmero de descargas actualmente: ",aux1)
	else:
github Pelhans / Z_knowledge_graph / ie / craw / craw_all_baidu / baidu_baike / pipelines.py View on Github external
def __init__(self):
        self.conn = pymysql.connect(
            host=settings.HOST_IP,
#            port=settings.PORT,
            user=settings.USER,
            passwd=settings.PASSWD,
            db=settings.DB_NAME,
            charset='utf8mb4',
            use_unicode=True
            )   
        self.cursor = self.conn.cursor()
        self.cursor.execute("SELECT MAX(title_id) FROM lemmas")
        max_id = self.cursor.fetchall()[0]
        if None in max_id:
            self.count = 1
        else:
            self.count = max_id[0]
github dbcli / mycli / mycli / packages / connection.py View on Github external
"""Connection and cursor wrappers around PyMySQL.

This module effectively backports PyMySQL functionality and error handling
so that mycli will support Debian's python-pymysql version (0.6.2).
"""

import pymysql

Cursor = pymysql.cursors.Cursor
connect = pymysql.connect


if pymysql.VERSION[1] == 6 and pymysql.VERSION[2] < 5:
    class Cursor(pymysql.cursors.Cursor):
        """Makes Cursor a context manager in PyMySQL < 0.6.5."""

        def __enter__(self):
            return self

        def __exit__(self, *exc_info):
            del exc_info
            self.close()


if pymysql.VERSION[1] == 6 and pymysql.VERSION[2] < 3:
    class Connection(pymysql.connections.Connection):