How do I connect to a MySQL Database in Python?

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

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

25条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 08:16

    Run this command in your terminal to install mysql connector:

    pip install mysql-connector-python
    

    And run this in your python editor to connect to MySQL:

    import mysql.connector
    
    mydb = mysql.connector.connect(
          host="localhost",
          user="yusername",
          passwd="password",
          database="database_name"
    )
    

    Samples to execute MySQL Commands (in your python edior):

    mycursor = mydb.cursor()
    mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")    
    mycursor.execute("SHOW TABLES")
    
    mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")    
    mydb.commit() # Use this command after insert or update
    

    For more commands: https://www.w3schools.com/python/python_mysql_getstarted.asp

提交回复
热议问题