How do I connect to a MySQL Database in Python?

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

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

25条回答
  •  没有蜡笔的小新
    2020-11-21 08:07

    Despite all answers above, in case you do not want to connect to a specific database upfront, for example, if you want to create the database still (!), you can use connection.select_db(database), as demonstrated in the following.

    import pymysql.cursors
    connection = pymysql.connect(host='localhost',
                             user='mahdi',
                             password='mahdi',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
    cursor = connection.cursor()
    cursor.execute("CREATE DATABASE IF NOT EXISTS "+database)
    connection.select_db(database)
    sql_create = "CREATE TABLE IF NOT EXISTS "+tablename+(timestamp DATETIME NOT NULL PRIMARY KEY)"
    cursor.execute(sql_create)
    connection.commit()
    cursor.close()
    

提交回复
热议问题