How do I connect to a MySQL Database in Python?

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

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

25条回答
  •  迷失自我
    2020-11-21 08:03

    Here's one way to do it, using MySQLdb, which only supports Python 2:

    #!/usr/bin/python
    import MySQLdb
    
    # Connect
    db = MySQLdb.connect(host="localhost",
                         user="appuser",
                         passwd="",
                         db="onco")
    
    cursor = db.cursor()
    
    # Execute SQL select statement
    cursor.execute("SELECT * FROM location")
    
    # Commit your changes if writing
    # In this case, we are only reading data
    # db.commit()
    
    # Get the number of rows in the resultset
    numrows = cursor.rowcount
    
    # Get and display one row at a time
    for x in range(0, numrows):
        row = cursor.fetchone()
        print row[0], "-->", row[1]
    
    # Close the connection
    db.close()
    

    Reference here

提交回复
热议问题