connections.py

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Pedrissimo
    New Member
    • Jan 2007
    • 4

    connections.py

    Does anyone know how to change the connections.py file in /usr/lib/python2.4/site-packages/MySQLdb/connections.py"
    to a specific user?

    The error I get is:

    _mysql_exceptio ns.OperationalE rror: (1045, "Access denied for user 'root'@'localho st' (using password: NO)")

    Attrched is the begiining of the file:
    Code:
    """
    
    This module implements connections for MySQLdb. Presently there is
    only one class: Connection. Others are unlikely. However, you might
    want to make your own subclasses. In most cases, you will probably
    override Connection.default_cursor with a non-standard Cursor class.
    
    """
    import cursors
    from _mysql_exceptions import Warning, Error, InterfaceError, DataError, \
         DatabaseError, OperationalError, IntegrityError, InternalError, \
         NotSupportedError, ProgrammingError
    import types, _mysql
    
    
    def defaulterrorhandler(connection, cursor, errorclass, errorvalue):
        """
    
        If cursor is not None, (errorclass, errorvalue) is appended to
        cursor.messages; otherwise it is appended to
        connection.messages. Then errorclass is raised with errorvalue as
        the value.
    
        You can override this with your own error handler by assigning it
        to the instance.
    
        """
        error = errorclass, errorvalue
        if cursor:
            cursor.messages.append(error)
        else:
            connection.messages.append(error)
        del cursor
        del connection
        raise errorclass, errorvalue
    
    
    class Connection(_mysql.connection):
    
        """MySQL Database Connection Object"""
    
        default_cursor = cursors.Cursor
        
        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
    Last edited by bartonc; Jan 21 '07, 09:03 PM. Reason: added [code][/code] tags
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    Hello and welcome to the Python forum on TSDN.
    The problem is not with /usr/lib/python2.4/site-packages/MySQLdb/connections.py
    The error I get is:

    _mysql_exceptio ns.OperationalE rror: (1045, "Access denied for user 'root'@'localho st' (using password: NO)")
    The problem is that way you are calling it. Please post your code (not the library code). I'll dig up some examples that I have written which will help.

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Originally posted by bartonc
      Hello and welcome to the Python forum on TSDN.
      The problem is not with /usr/lib/python2.4/site-packages/MySQLdb/connections.py"

      The problem is that way you are calling it. Please post your code (not the library code). I'll dig up some examples that I have written which will help.
      If this is a shared machine on "unix" you will most likely NOT have a root login and you will need the admin to create an account for you. If this is your own machine or you have an account already set up then you can get a connection like this:
      Code:
      from MySQLdb import *
      # replace servername, username and password with your account info
      dbconnect = connect(host=servername, user=username, passwd=password)
      dbcursor = dbconnect.cursor()
      # once you have a cursor, you can send SQL commands to the DB, like:
      dbcursor.execute('SET autocommit=1')
      Here are some useful classes and helper functions that I wrote.

      Comment

      • Pedrissimo
        New Member
        • Jan 2007
        • 4

        #4
        Hi and thanks for getting back to me here is the code you asked for...

        and the error again

        _mysql_exceptio ns.OperationalE rror: (1045, "Access denied for user 'root'@'localho st' (using password: NO)")

        Code:
        import MySQLdb
        import os
        from splicegraph_jan06 import *
        
        spliceCalcs={'hg17_JAN06':
                     TableGroup(db='SPLICE_JAN06',suffix='hg17',clusters='cluster_hg17',
                                exons='isoform_exon_form_hg17',splices='splice_verificat
        ion_hg17',
                                genomic='genomic_cluster_hg17',mrna='isoform_mrna_seq_hg
        17',
                                protein='isoform_protein_seq_hg17'),
                     'mm7_JAN06':
                     TableGroup(db='SPLICE_JAN06',suffix='mm7',clusters='cluster_mm17',
                                exons='isoform_exon_form_mm7',splices='splice_verificati
        on_mm7',
                                genomic='genomic_cluster_mm7',mrna='isoform_mrna_seq_mm7
        ',
                                protein='isoform_protein_seq_mm7')
                     }
        
        
        def getUserCursor(db):
            'get a cursor as the current user'
            db=MySQLdb.connect(db=db,read_default_file=os.environ['HOME']+'/.my.cnf',com
        press=True)
            return db.cursor()
                     
        def getSpliceGraphFromDB(dbgroup,loadAll=False):
            """load data from MySQL using the designated database table group.
            If loadAll true, then load the entire splice graph into memory."""
            cursor=getUserCursor(dbgroup.db)
            import sys
            print >>sys.stderr,'Reading database schema...'
            idDict={}
            tables=describeDBTables(dbgroup.db,cursor,idDict)
            if hasattr(dbgroup,'suffix'):
                tables=suffixSubset(tables,dbgroup.suffix) # SET OF TABLES ENDING IN JUN
        03
                idDict=indexIDs(tables) # CREATE AN INDEX OF THEIR PRIMARY KEYS
            for t in dbgroup.values():
                if t is not None and '.' in t and t not in tables: # THIS TABLE COMES FR
        OM ANOTHER DATABASE...
                    tables[t]=SQLTable(t,cursor) # SO GET IT FROM OTHER DATABASE
        
            # LOAD DATA & BUILD THE SPLICE GRAPH
            return loadSpliceGraph(tables,dbgroup.clusters,dbgroup.exons,dbgroup.splices
        ,
                                   dbgroup.genomic,dbgroup.mrna,dbgroup.protein,loadAll)
        
        def localCopy(localFile,cpCommand):
            'if not already present on local file location, run cpCommand'
            if not os.access(localFile,os.R_OK):
                cmd=cpCommand % localFile
                print 'copying data:',cmd
                exit_code=os.system(cmd)
                if exit_code!=0:
                    raise OSError((exit_code,'command failed: %s' % cmd))
            return localFile
        Last edited by bartonc; Jan 22 '07, 06:13 AM. Reason: added [code][/code] tags

        Comment

        • bartonc
          Recognized Expert Expert
          • Sep 2006
          • 6478

          #5
          Originally posted by Pedrissimo
          Hi and thanks for getting back to me here is the code you asked for...

          and the error again

          _mysql_exceptio ns.OperationalE rror: (1045, "Access denied for user 'root'@'localho st' (using password: NO)")

          Code:
          import MySQLdb
          import os
          def getUserCursor(db):
              'get a cursor as the current user'
              db=MySQLdb.connect(db=db,read_default_file=os.environ['HOME']+'/.my.cnf',com
          press=True)
              return db.cursor()
          First I'd see if you can make this work
          Code:
          # replace servername, username and password with your account info
          dbconnect = connect(host=servername, user=username, passwd=password)
          dbcursor = dbconnect.cursor()
          Then, if that works, check to see if your
          my.cnf
          is set up correctly. I should look like this:
          You can specify connection parameters in the [client] section of an option file. The relevant section of the file might look like this:
          [client]
          host=host_name
          user=user_name
          password=your_p ass
          Section 4.3.2, “Using Option Files”, discusses option files further.
          according to MySQL docs.
          It also looks like you can specify other that "client" group using
          read_default_gr oup
          configuration group to use from the default file
          but mysqld docs are not very clear on that.

          Comment

          • Pedrissimo
            New Member
            • Jan 2007
            • 4

            #6
            Hi again,

            I enter the following lines you recommend

            dbconnect = connect(host=ho stname, user=root, passwd=*******)
            dbcursor = dbconnect.curso r()

            and get the following error?

            File "/home/pedro/pygr/tests/lldb_jan06.py", line 22, in ?
            dbconnect = connect(host=ho stname, user=root, passwd=*******)
            NameError: name 'connect' is not defined


            Originally posted by bartonc
            First I'd see if you can make this work
            Code:
            # replace servername, username and password with your account info
            dbconnect = connect(host=servername, user=username, passwd=password)
            dbcursor = dbconnect.cursor()
            Then, if that works, check to see if your
            my.cnf
            is set up correctly. I should look like this:
            You can specify connection parameters in the [client] section of an option file. The relevant section of the file might look like this:
            [client]
            host=host_name
            user=user_name
            password=your_p ass
            Section 4.3.2, “Using Option Files”, discusses option files further.
            according to MySQL docs.
            It also looks like you can specify other that "client" group using
            read_default_gr oup
            configuration group to use from the default file
            but mysqld docs are not very clear on that.

            Comment

            • bartonc
              Recognized Expert Expert
              • Sep 2006
              • 6478

              #7
              Originally posted by Pedrissimo
              Hi again,

              I enter the following lines you recommend

              dbconnect = connect(host=ho stname, user=root, passwd=*******)
              dbcursor = dbconnect.curso r()

              and get the following error?

              File "/home/pedro/pygr/tests/lldb_jan06.py", line 22, in ?
              dbconnect = connect(host=ho stname, user=root, passwd=*******)
              NameError: name 'connect' is not defined
              Sorry, that was a snippet.. should be:
              Code:
              from MySQLdb import *
              dbconnect = connect(host=hostname, user=root, passwd=*******)
              dbcursor = dbconnect.cursor()
              as in my reply #3 above.

              Comment

              • Pedrissimo
                New Member
                • Jan 2007
                • 4

                #8
                Ok that worked but now I get another error from a second py program...

                File "/home/pedro/pygr/tests/lldb_jan06.py", line 34, in getSpliceGraphF romDB
                tables=describe DBTables(dbgrou p.db,cursor,idD ict)
                File "/usr/lib/python2.4/site-packages/pygr/sqlgraph.py", line 212, in describeDBTable s
                cursor.execute( 'use %s' % name)
                AttributeError: 'NoneType' object has no attribute 'execute'

                Here is the portion of the script:

                Code:
                def describeDBTables(name,cursor,idDict):
                    """
                    Get table info about database <name> via <cursor>, and store primary keys
                    in idDict, along with a list of the tables each key indexes.
                    """
                    cursor.execute('use %s' % name)
                    cursor.execute('show tables')
                    tables={}
                    l=[c[0] for c in cursor.fetchall()]
                    for t in l:
                tname=name+'.'+ t
                o=SQLTable(tnam e,cursor)
                [/CODE]

                and the original change from the other py script


                [CODE]
                def getUserCursor(d b):
                'get a cursor as the current user'
                #db=MySQLdb.con nect(db=db,read _default_file=o s.environ['HOME']+'/.my.cnf',com
                #press=True)
                # return db.cursor()
                from MySQLdb import *
                dbconnect = connect(host='l ocalhost', user='root', passwd='retep1e r')
                dbcursor = dbconnect.curso r()
                [CODE]

                Incidentally I changed my /etc/mysql/my.cnf file (my only my.cnf) file

                [client]
                [client]
                user = 'root'
                password = '********'
                port = 3306
                socket = /var/run/mysqld/mysqld.sock

                with the original configuration of the py file

                [CODE]
                def getUserCursor(d b):
                'get a cursor as the current user'
                db=MySQLdb.conn ect(db=db,read_ default_file=os .environ['HOME']+'/.my.cnf',com
                press=True)
                return db.cursor()

                [\CODE]

                and this produced the original error?

                Comment

                • bartonc
                  Recognized Expert Expert
                  • Sep 2006
                  • 6478

                  #9
                  Originally posted by bartonc
                  If this is a shared machine on "unix" you will most likely NOT have a root login and you will need the admin to create an account for you. If this is your own machine or you have an account already set up then you can get a connection like this:
                  Code:
                  from MySQLdb import *
                  # replace servername, username and password with your account info
                  dbconnect = connect(host=servername, user=username, passwd=password)
                  dbcursor = dbconnect.cursor()
                  # once you have a cursor, you can send SQL commands to the DB, like:
                  dbcursor.execute('SET autocommit=1')
                  Here are some useful classes and helper functions that I wrote.
                  Here for error handling example.

                  Comment

                  Working...