How do I connect to a MySQL Database in Python?

后端 未结 25 1508
眼角桃花
眼角桃花 2020-11-21 07:43

How do I connect to a MySQL database using a python program?

相关标签:
25条回答
  • 2020-11-21 08:27

    first install the driver

    pip install MySQL-python   
    

    Then a basic code goes like this:

    #!/usr/bin/python
    import MySQLdb
    
    try:
        db = MySQLdb.connect(host="localhost",      # db server, can be a remote one 
                         db="mydb"                  # database
                         user="mydb",               # username
                         passwd="mydb123",          # password for this username
                         )        
    
        # Create a Cursor object
        cur = db.cursor()
    
        # Create a query string. It can contain variables
        query_string = "SELECT * FROM MY_TABLE"
    
        # Execute the query
        cur.execute(query_string)
    
        # Get all the rows present the database
        for each_row in cur.fetchall():
            print each_row
    
        # Close the connection
        db.close()
    except Exception, e:
        print 'Error ', e 
    
    0 讨论(0)
提交回复
热议问题