Low Orbit Flux Logo 2 F

How to Insert User Input into MySQL Database in Python

We are going to show you how to insert user input into MySQL database with Python.

Install the connector first:



pip install mysql-connector-python

The use this example script ( substitute in your own parameters ):



import mysql.connector

db = mysql.connector.connect(
    host="localhost",
    user="user1",
    password="secret_password4!",
    database="db1"
)

cursor = db.cursor()
username = input("Enter username: ")
email = input("Enter email: ")

insert_query = "INSERT INTO users (username, email) VALUES (%s, %s)"
values = (username, email)

cursor.execute(insert_query, values)
db.commit()

cursor.close()
db.close()

Note that in the above example we didn’t sanitize the input so you might not want to use this in production without adding that functionality.