How do I connect to a MySQL Database in Python?

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

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

25条回答
  •  终归单人心
    2020-11-21 08:23

    If you do not need MySQLdb, but would accept any library, I would very, very much recommend MySQL Connector/Python from MySQL: http://dev.mysql.com/downloads/connector/python/.

    It is one package (around 110k), pure Python, so it is system independent, and dead simple to install. You just download, double-click, confirm license agreement and go. There is no need for Xcode, MacPorts, compiling, restarting …

    Then you connect like:

    import mysql.connector    
    cnx = mysql.connector.connect(user='scott', password='tiger',
                                  host='127.0.0.1',
                                  database='employees')
    
    try:
       cursor = cnx.cursor()
       cursor.execute("""
          select 3 from your_table
       """)
       result = cursor.fetchall()
       print result
    finally:
        cnx.close()
    

提交回复
热议问题