Python MySQLdb.connect() Examples

The following are 30 code examples for showing how to use MySQLdb.connect(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module MySQLdb , or try the search function .

Example 1
Project: redditswapbot   Author: thelectronicnub   File: mySQLHandler.py    License: GNU General Public License v3.0 6 votes vote down vote up
def emit(self, record):
        """
        Connect to DB, execute SQL Request, disconnect from DB
        @param record:
        @return: 
        """ 
        # Use default formatting:
        self.format(record)
        # Set the database time up:
        self.formatDBTime(record)
        if record.exc_info:
            record.exc_text = logging._defaultFormatter.formatException(record.exc_info)
        else:
            record.exc_text = ""
        # Insert log record:
        sql = mySQLHandler.insertion_sql
        try:
            conn=MySQLdb.connect(host=self.db['host'],port=self.db['port'],user=self.db['dbuser'],passwd=self.db['dbpassword'],db=self.db['dbname'])
        except _mysql_exceptions, e:
            from pprint import pprint
            print("The Exception during db.connect")           
            pprint(e)
            raise Exception(e)
            exit(-1) 
Example 2
Project: PythonClassBook   Author: PythonClassRoom   File: DBSetup.py    License: GNU General Public License v3.0 6 votes vote down vote up
def buildDatabase( databaseName ):

   username = raw_input( "Enter MySQL user name: " )
   password = getpass.getpass( "Enter user password: " )

   print "Creating database %s:" % databaseName

   # retrieve database description from file
   print "\tRetrieving database definition:",

   try:
      databaseDefinition = retrieveDatabaseDefinition( databaseName )
   except TypeError:
      sys.exit( "ERROR\nThe database definition in %s.def is invalid" % databaseName )
   else:
      print "DONE"

   # get a cursor for MySQL
   print "\tConnecting to MySQL:",
   try:
      cursor = MySQLdb.connect( user = username, passwd = password ).cursor()
   except MySQLdb.OperationalError, error:
      sys.exit( "ERROR\nCould not connect to MySQL (%s)" % error ) 
Example 3
Project: magpy   Author: geomagpy   File: database.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dbgetstring(db,tablename,sensorid,columnid,revision=None):
    """
    DEFINITION:
        Perform a select search and return strings
    PARAMETERS:
    Variables:
        - db:           (mysql database) defined by mysql.connect().
        - tablename:    name of the table
        - sensorid:     sensor to match
        - columnid:     column in which search is performed
    Kwargs:
        - revision:     optional sensor revision (not used so far)
    APPLICATION:
        >>>stationid =  dbgetstring(db, 'DATAINFO', 'LEMI25_22_0001', 'StationID')
        returns the stationid from the DATAINFO table which matches the Sensor
    """
    sql = 'SELECT ' + columnid + ' FROM ' + tablename + ' WHERE SensorID = "' + sensorid + '"';
    cursor = db.cursor()
    cursor.execute(sql)
    row = cursor.fetchone()
    try:
        fl = float(row[0])
        return fl
    except:
        return row[0] 
Example 4
Project: Penny-Dreadful-Tools   Author: PennyDreadfulMTG   File: database.py    License: GNU General Public License v3.0 6 votes vote down vote up
def execute_with_reconnect(self, sql: str, args: Optional[List[ValidSqlArgumentDescription]] = None, fetch_rows: Optional[bool] = False) -> Tuple[int, List[ValidSqlArgumentDescription]]:
        result = None
        # Attempt to execute the query and reconnect 3 times, then give up
        for _ in range(3):
            try:
                p = perf.start()
                n = self.cursor.execute(sql, args)
                perf.check(p, 'slow_query', (f'```{sql}```', f'```{args}```'), 'mysql')
                if fetch_rows:
                    rows = self.cursor.fetchall()
                    result = (n, rows)
                else:
                    result = (n, [])
                break
            except OperationalError as e:
                if 'MySQL server has gone away' in str(e):
                    print('MySQL server has gone away: trying to reconnect')
                    self.connect()
                else:
                    # raise any other exception
                    raise e
        else:
            # all attempts failed
            raise DatabaseException('Failed to execute `{sql}` with `{args}`. MySQL has gone away and it was not possible to reconnect in 3 attemps'.format(sql=sql, args=args))
        return result 
Example 5
Project: python-mysql-pool   Author: LuciferJack   File: mysql_util.py    License: MIT License 6 votes vote down vote up
def query_single(_db_config, _sql, _args):
    config = _db_config
    conn = MySQLdb.connect(host=config['host'], port=config['port'], user=config['user'], passwd=config['passwd'],
                           db=config['db'], charset=config['charset'], use_unicode=True)
    cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    result = ()
    try:
        cursor.execute(_sql, _args)
        result = cursor.fetchall()
    except:
        pass
        rootLogger.error("query exception sql is %s ,_args is %s,stacks is %s", _sql, _args, get_caller_info_total())
        rootLogger.exception("message")
    finally:
        cursor.close()
        conn.close()
    return result


# ===============================================
# FUNCTION  更新或者删除
# =============================================== 
Example 6
Project: python-mysql-pool   Author: LuciferJack   File: mysql_util.py    License: MIT License 6 votes vote down vote up
def insertOrUpdate_getId(_db_config, _sql, _args):
    result = 0
    id = 0
    config = _db_config
    conn = MySQLdb.connect(host=config['host'], port=config['port'], user=config['user'], passwd=config['passwd'],
                           db=config['db'], charset=config['charset'], use_unicode=True)
    cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    try:
        cursor.execute(_sql, _args)
        id = conn.insert_id()
        conn.commit()
        result = cursor.rowcount
    except:
        pass
        rootLogger.error("exception sql is %s ,_args is %s", _sql, _args)
        rootLogger.exception("message")
        conn.rollback()
    finally:
        print("affected rows = {}".format(cursor.rowcount))
        cursor.close()
        conn.close()
    return result, id 
Example 7
Project: SempoBlockchain   Author: teamsempo   File: rds_migrate.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, sempo_organisation_id, ge_community_token_id=None, user_limit=10000):
        self.poa = POAExplorer()
        timeout = 120
        print('RDSMigrate: Creating a connection, with a %d sec timeout.' % timeout)
        self.connection = MySQLdb.connect(host=current_app.config['GE_DB_HOST'],
                                          db=current_app.config['GE_DB_NAME'],
                                          user=current_app.config['GE_DB_USER'],
                                          port=int(current_app.config['GE_DB_PORT']),
                                          password=current_app.config['GE_DB_PASSWORD'],
                                          connect_timeout=timeout)

        if not self.connection:
            raise RuntimeError('Could not connect to database')
        else:
            print('DB connection successfully created.  Yeah us.')

        self.sempo_organisation_id = sempo_organisation_id
        self.ge_community_token_id = ge_community_token_id
        self.user_limit = user_limit 
Example 8
Project: openmano   Author: nfvlabs   File: vim_db.py    License: Apache License 2.0 6 votes vote down vote up
def connect(self, host=None, user=None, passwd=None, database=None):
        '''Connect to the concrete data base. 
        The first time a valid host, user, passwd and database must be provided,
        Following calls can skip this parameters
        '''
        try:
            if host     is not None: self.host = host
            if user     is not None: self.user = user
            if passwd   is not None: self.passwd = passwd
            if database is not None: self.database = database

            self.con = mdb.connect(self.host, self.user, self.passwd, self.database)
            self.logger.debug("connected to DB %s at %s@%s", self.database,self.user, self.host)
            return 0
        except mdb.Error as e:
            self.logger.error("Cannot connect to DB %s at %s@%s Error %d: %s", self.database, self.user, self.host, e.args[0], e.args[1])
            return -1 
Example 9
Project: openmano   Author: nfvlabs   File: nfvo_db.py    License: Apache License 2.0 6 votes vote down vote up
def connect(self, host=None, user=None, passwd=None, database=None):
        '''Connect to specific data base. 
        The first time a valid host, user, passwd and database must be provided,
        Following calls can skip this parameters
        '''
        try:
            if host     is not None: self.host = host
            if user     is not None: self.user = user
            if passwd   is not None: self.passwd = passwd
            if database is not None: self.database = database

            self.con = mdb.connect(self.host, self.user, self.passwd, self.database)
            print "DB: connected to %s@%s -> %s" % (self.user, self.host, self.database)
            return 0
        except mdb.Error, e:
            print "nfvo_db.connect Error connecting to DB %s@%s -> %s Error %d: %s" % (self.user, self.host, self.database, e.args[0], e.args[1])
            return -1 
Example 10
Project: Computable   Author: ktraunmueller   File: test_sql.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        _skip_if_no_MySQLdb()
        import MySQLdb
        try:
            # Try Travis defaults.
            # No real user should allow root access with a blank password.
            self.db = MySQLdb.connect(host='localhost', user='root', passwd='',
                                    db='pandas_nosetest')
        except:
            pass
        else:
            return
        try:
            self.db = MySQLdb.connect(read_default_group='pandas')
        except MySQLdb.ProgrammingError as e:
            raise nose.SkipTest(
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf. ")
        except MySQLdb.Error as e:
            raise nose.SkipTest(
                "Cannot connect to database. "
                "Create a group of connection parameters under the heading "
                "[pandas] in your system's mysql default file, "
                "typically located at ~/.my.cnf or /etc/.my.cnf. ") 
Example 11
Project: verejne.digital   Author: verejnedigital   File: geocode_db_utils.py    License: Apache License 2.0 6 votes vote down vote up
def execute(cur, sql, params=[]):
    global args
    if not (args.sql_silent):
        log("SQL: " + sql)
        log("PARAMS: " + str(params))
    if args.dryrun:
        if not (("select" in sql.lower()) or ("show columns" in sql.lower())):
            print "Not executing, dryrun"
            return
    try:
    	  cur.execute(sql, params)
    except Exception as ex:
        print "Exception in SQL execution, retrying command once"
        print ex
        connect(False)
        cur = getCursor()
        cur.execute(sql, params)
    return cur 
Example 12
Project: iOS-private-api-checker   Author: NetEaseGame   File: db_connect_warp.py    License: GNU General Public License v2.0 6 votes vote down vote up
def require_db_connection(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        ####连接数据库
        if hasattr(g, 'conn') and g.conn != None and hasattr(g, 'cursor') and g.cursor != None:
            print 'has db connect, do nothing'
        else:
            (g.conn, g.cursor) = _connect_db()
            print 'create new db connect'
        
        #执行方法
        func = f(*args, **kwargs)
        
        ###关闭数据库连接
        if hasattr(g, 'conn') and g.conn != None and hasattr(g, 'cursor') and g.cursor != None:
            g.cursor.close()
            g.cursor = None 
            g.conn.close()
            g.conn = None
            print 'close db connect'
        else:
            print 'no db connect, no need to close...'
        
        return func
    return decorated_function 
Example 13
Project: zappa-django-utils   Author: Miserlou   File: create_mysql_db.py    License: MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting db creation'))

        dbname = options.get('db_name') or settings.DATABASES['default']['NAME']
        user = options.get('user') or settings.DATABASES['default']['USER']
        password = options.get('password') or settings.DATABASES['default']['PASSWORD']
        host = settings.DATABASES['default']['HOST']

        con = db.connect(user=user, host=host, password=password)
        cur = con.cursor()
        cur.execute(f'CREATE DATABASE {dbname}')
        cur.execute(f'ALTER DATABASE `{dbname}` CHARACTER SET utf8')
        cur.close()
        con.close()

        self.stdout.write(self.style.SUCCESS('All Done')) 
Example 14
Project: airflow   Author: apache   File: mysql.py    License: Apache License 2.0 6 votes vote down vote up
def get_iam_token(self, conn):
        """
        Uses AWSHook to retrieve a temporary password to connect to MySQL
        Port is required. If none is provided, default 3306 is used
        """
        from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook

        aws_conn_id = conn.extra_dejson.get('aws_conn_id', 'aws_default')
        aws_hook = AwsBaseHook(aws_conn_id, client_type='rds')
        if conn.port is None:
            port = 3306
        else:
            port = conn.port
        client = aws_hook.get_conn()
        token = client.generate_db_auth_token(conn.host, port, conn.login)
        return token, port 
Example 15
Project: redditswapbot   Author: thelectronicnub   File: mySQLHandler.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, db):
        """
        Constructor
        @param db: ['host','port','dbuser', 'dbpassword', 'dbname'] 
        @return: mySQLHandler
        """
        
        logging.Handler.__init__(self)
        self.db = db
        # Try to connect to DB

        # Check if 'log' table in db already exists
        result = self.checkTablePresence()
        # If not exists, then create the table
        if not result:
            try:
                conn=MySQLdb.connect(host=self.db['host'],port=self.db['port'],user=self.db['dbuser'],passwd=self.db['dbpassword'],db=self.db['dbname'])
            except _mysql_exceptions, e:
                raise Exception(e)
                exit(-1)
            else:         
                cur = conn.cursor()
                try:
                    cur.execute(mySQLHandler.initial_sql)
                except _mysql_exceptions as e:
                    conn.rollback()
                    cur.close()
                    conn.close()
                    raise Exception(e)
                    exit(-1)
                else:
                    conn.commit()
                finally:
                    cur.close()
                    conn.close() 
Example 16
Project: redditswapbot   Author: thelectronicnub   File: mySQLHandler.py    License: GNU General Public License v3.0 5 votes vote down vote up
def checkTablePresence(self):
        try:
            conn=MySQLdb.connect(host=self.db['host'],port=self.db['port'],user=self.db['dbuser'],passwd=self.db['dbpassword'],db=self.db['dbname'])
        except _mysql_exceptions, e:
            raise Exception(e)
            exit(-1) 
Example 17
Project: PythonClassBook   Author: PythonClassRoom   File: fig17_30.py    License: GNU General Public License v3.0 5 votes vote down vote up
def addAddress( self ):
      """Add address record to database"""

      if self.entries[ "LAST_NAME" ].get() != "" and \
         self.entries[ "FIRST_NAME"].get() != "":

         # create INSERT query command
         query = """INSERT INTO addresses (  
                 FIRST_NAME, LAST_NAME, ADDRESS, CITY,
                 STATE_PROVINCE, POSTAL_CODE, COUNTRY,
                 EMAIL_ADDRESS, HOME_PHONE, FAX_NUMBER
                 ) VALUES (""" + \
                 "'%s', " * 10 % \
                 ( self.entries[ "FIRST_NAME" ].get(),
                   self.entries[ "LAST_NAME" ].get(),
                   self.entries[ "ADDRESS" ].get(),
                   self.entries[ "CITY" ].get(),
                   self.entries[ "STATE_PROVINCE" ].get(),
                   self.entries[ "POSTAL_CODE" ].get(),
                   self.entries[ "COUNTRY" ].get(),
                   self.entries[ "EMAIL_ADDRESS" ].get(),
                   self.entries[ "HOME_PHONE" ].get(),
                   self.entries[ "FAX_NUMBER" ].get() )
         query = query[ :-2 ] + ")"

         # open connection, retrieve cursor and execute query
         try:      
            connection = MySQLdb.connect( db = "AddressBook" )
            cursor = connection.cursor()
            cursor.execute( query ) 
         except MySQLdb.OperationalError, message:
            errorMessage = "Error %d:\n%s" % \
               ( message[ 0 ], message[ 1 ] )
            showerror( "Error", errorMessage )
         else:
            cursor.close()
            connection.close()
	    self.clearContents() 
Example 18
Project: PythonClassBook   Author: PythonClassRoom   File: fig17_30.py    License: GNU General Public License v3.0 5 votes vote down vote up
def findAddress( self ):
      """Query database for address record and display results"""

      if self.entries[ "LAST_NAME" ].get() != "":

         # create SELECT query
         query = "SELECT * FROM addresses " + \
                 "WHERE LAST_NAME = '" + \
                 self.entries[ "LAST_NAME" ].get() + "'"

         # open connection, retrieve cursor and execute query
         try:      
            connection = MySQLdb.connect( db = "AddressBook" )
            cursor = connection.cursor()
            cursor.execute( query )
         except MySQLdb.OperationalError, message:
            errorMessage = "Error %d:\n%s" % \
               ( message[ 0 ], message[ 1 ] )
            showerror( "Error", errorMessage )
            self.clearContents()
         else:   # process results
            results = cursor.fetchall()
            fields = cursor.description

            if not results:   # no results for this person
               showinfo( "Not found", "Nonexistent record" )
            else:             # display person's info. in GUI
               self.clearContents()

               # display results
               for i in range( len( fields ) ):

                  if fields[ i ][ 0 ] == "ID":
                     self.IDEntry.set( str( results[ 0 ][ i ] ) )
                  else:
                     self.entries[ fields[ i ][ 0 ] ].insert( 
                        INSERT, str( results[ 0 ][ i ] ) )
            
            cursor.close()
            connection.close() 
Example 19
Project: PythonClassBook   Author: PythonClassRoom   File: fig17_30.py    License: GNU General Public License v3.0 5 votes vote down vote up
def updateAddress( self ):
      """Update address record in database"""

      if self.entries[ "ID" ].get() != "":

         # create UPDATE query command
         entryItems = self.entries.items()
         query = "UPDATE addresses SET"

         for key, value in entryItems:
            
            if key != "ID":
               query += " %s='%s'," % ( key, value.get() )

         query = query[ :-1 ] + " WHERE ID=" + self.IDEntry.get()

         # open connection, retrieve cursor and execute query
         try:      
            connection = MySQLdb.connect( db = "AddressBook" )
            cursor = connection.cursor()
            cursor.execute( query ) 
         except MySQLdb.OperationalError, message:
            errorMessage = "Error %d:\n%s" % \
               ( message[ 0 ], message[ 1 ] )
            showerror( "Error", errorMessage )
            self.clearContents()
         else:
            showinfo( "database updated", "Database Updated." )
            cursor.close()
            connection.close() 
Example 20
Project: PythonClassBook   Author: PythonClassRoom   File: fig17_29.py    License: GNU General Public License v3.0 5 votes vote down vote up
def submitQuery( self ):
      """Execute user-entered query agains database"""

      # open connection, retrieve cursor and execute query
      try:      
         connection = MySQLdb.connect( db = "Books" )
         cursor = connection.cursor()
         cursor.execute( self.query.get() )
      except MySQLdb.OperationalError, message:
         errorMessage = "Error %d:\n%s" % \
            ( message[ 0 ], message[ 1 ] )
         showerror( "Error", errorMessage )
         return 
Example 21
Project: Jamais-Vu   Author: CwbhX   File: database_sql.py    License: MIT License 5 votes vote down vote up
def __init__(self, cursor_type=mysql.cursors.Cursor, **options):
        super(Cursor, self).__init__()

        try:
            conn = self._cache.get_nowait()
        except Queue.Empty:
            conn = mysql.connect(**options)
        else:
            # Ping the connection before using it from the cache.
            conn.ping(True)

        self.conn = conn
        self.conn.autocommit(False)
        self.cursor_type = cursor_type 
Example 22
Project: JetPack   Author: dsp-jetpack   File: mysql_db.py    License: Apache License 2.0 5 votes vote down vote up
def __get_connection__(self):
        return MySQLdb.connect(self.host, self.user,
                               self.passwd, self.db_name) 
Example 23
Project: coursys   Author: sfu-fas   File: svn.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _db_conn():
    dbconn = MySQLdb.connect(**settings.SVN_DB_CONNECT)
    return dbconn.cursor() 
Example 24
Project: yamdwe   Author: projectgus   File: yamdwe_users.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_mediawiki_users(host, user, password, dbname, tableprefix):
    print(host,user,password,dbname,tableprefix)
    db = MySQLdb.connect(passwd=password, user=user, host=host, db=dbname,
                         use_unicode=True, charset="utf8")
    c = db.cursor()
    c.execute("SELECT user_name,user_real_name,user_email,user_password FROM %suser" % tableprefix)
    users = {}

    def _escape(field):
        if isinstance(field,unicode):
            return field.replace(":", r"\:")
        else:
            return unicode(field, "utf-8").replace(":", r"\:")

    for row in c.fetchall():
        login = names.clean_user(unicode(row[0], "utf-8"))
        users[login] = {
            "login" : login,
            "pwhash" : _escape(row[3]),
            "name" : _escape(row[1]),
            "email" : _escape(row[2]),
            "groups" : "user",
            }
    return users

# Parser for command line arguments 
Example 25
Project: autopython   Author: wing324   File: rename_mysql_database.py    License: GNU General Public License v3.0 5 votes vote down vote up
def conn_mysql():
	verbose("Connecting to MySQL......")
	if args.prompt_password:
		password=getpass.getpass("Please input your MySQL password:")
	else:
		password = args.password
	conn = MySQLdb.connect(user=args.user,host=args.host,port=args.port,unix_socket=args.socket,passwd=args.password,db=args.old_database,cursorclass=MySQLdb.cursors.DictCursor)
	return conn
	# 建立MySQL连接
	# connect to MySQL 
Example 26
Project: browserscope   Author: elsigh   File: uploader.py    License: Apache License 2.0 5 votes vote down vote up
def Connect(default_file):
  return MySQLdb.connect(read_default_file=default_file) 
Example 27
Project: browserscope   Author: elsigh   File: local_scores.py    License: Apache License 2.0 5 votes vote down vote up
def main(argv):
  host, user, params, mysql_default_file, argv = ParseArgs(argv)
  start = datetime.datetime.now()
  db = MySQLdb.connect(read_default_file=mysql_default_file)
  #DumpScores(db)
  rankers = BuildRankers(db)
  DumpRankers(sys.stdout, rankers)
  #CheckTests(db)
  end = datetime.datetime.now()
  logging.info('  start: %s', start)
  logging.info('    end: %s', end)
  logging.info('elapsed: %s', str(end - start)[:-7]) 
Example 28
Project: dbpy   Author: whiteclover   File: connection.py    License: GNU General Public License v2.0 5 votes vote down vote up
def connect(self):
        self.close()
        self._connect = MySQLdb.connect(**self._db_options)
        self._connect.autocommit(True) 
Example 29
Project: dbpy   Author: whiteclover   File: connection.py    License: GNU General Public License v2.0 5 votes vote down vote up
def ensure_connect(self):
        if not self._connect or self._max_idle < (time.time() - self._last_used):
            try:
                self._connect.ping()
            except:
                self.connect()
        self._last_used = time.time() 
Example 30
Project: magpy   Author: geomagpy   File: database.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dbinfo(db,destination='log',level='full'):
    """
    DEFINITION:
        Provide version info of database and write to log
    PARAMETERS:
        - db:           (mysql database) defined by mysql.connect().
        - destination:  (string) either "log"(default) or "stdout"  
        - level:        (string) "full"(default) -> show size as well, else skip size  
    """

    size = 'not determined'
    versionsql = "SELECT VERSION()"
    namesql = "SELECT DATABASE()"
    cursor = db.cursor()
    cursor.execute(versionsql)
    version = cursor.fetchone()[0]
    cursor.execute(namesql)
    databasename = cursor.fetchone()[0]
    if level == 'full':
        sizesql = 'SELECT sum(round(((data_length + index_length) / 1024 / 1024 / 1024), 2)) as "Size in GB" FROM information_schema.TABLES WHERE table_schema="{}"'.format(databasename)
        cursor.execute(sizesql)
        size = cursor.fetchone()[0]
    if destination == 'log':
        loggerdatabase.info("connected to database '{}' (MYSQL Version {}) - size in GB: {}".format(databasename,version,size))
    else:
        print ("connected to database '{}' (MYSQL Version {}) - size in GB: {}".format(databasename,version,size))
    db.commit()
    cursor.close()