In python, you can use cursor.execute()
to execute an Insert sql statement to insert a row to mysql table.
Syntax
cursor.execute(“INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...)”)
Insert a New User
import mysql.connector # Establish connection to MySQL server connection = mysql.connector.connect( host="localhost", user="root", password="password", database="mydatabase" ) cursor = connection.cursor() # Insert a new record into the 'users' table insert_query = "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')" cursor.execute(insert_query) # Commit the changes connection.commit() # Verify the insert cursor.execute("SELECT * FROM users WHERE name = 'Alice'") new_user = cursor.fetchone() print("New User:", new_user) connection.close()
Important: You should use connection.commit()
to make the changes permanently.