How do I connect to a MySQL Database in Python?

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

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

25条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 08:22

    First install the driver (Ubuntu)

    • sudo apt-get install python-pip

    • sudo pip install -U pip

    • sudo apt-get install python-dev libmysqlclient-dev

    • sudo apt-get install MySQL-python

    MySQL database connection codes

    import MySQLdb
    conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "pass",db = "dbname")
    cursor = conn.cursor ()
    cursor.execute ("SELECT VERSION()")
    row = cursor.fetchone ()
    print "server version:", row[0]
    cursor.close ()
    conn.close ()
    

提交回复
热议问题