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 do I connect to XAMPP MySQL using Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect Python to a MySQL database?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a Python MySQL refresh cursor?
- How do I use a cursor to interact with a MySQL database in Python?
See more codes...