python-mysqlHow do I set up an auto-incrementing primary key in a MySQL table using Python?
To set up an auto-incrementing primary key in a MySQL table using Python, you can use the MySQL Connector/Python library.
The following example code will create a table called users
with an auto-incrementing primary key column called id
:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password"
)
mycursor = mydb.cursor()
sql = "CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))"
mycursor.execute(sql)
The above code will create a table called users
with an auto-incrementing primary key column called id
.
The parts of the code are as follows:
import mysql.connector
: imports the MySQL Connector/Python librarymydb = mysql.connector.connect(host="localhost", user="user", passwd="password")
: connects to the MySQL databasemycursor = mydb.cursor()
: creates a cursor object to execute SQL statementssql = "CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))"
: creates a SQL statement to create a table with an auto-incrementing primary keymycursor.execute(sql)
: executes the SQL statement
Helpful links
More of Python Mysql
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I convert a MySQL database to a SQLite database using Python?
- How do I download MySQL-Python 1.2.5 zip file?
- How do I access MySQL using Python?
- How can I export data from a MySQL database to a CSV file using Python?
- How can I connect Python and MySQL?
- How can I use Python to interact with a MySQL database using YAML?
- How do I set up a secure SSL connection between Python and MySQL?
- How do I install a Python package from PyPI into a MySQL database?
See more codes...