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 download MySQL-Python 1.2.5 zip file?
- How can I access MySQL using Python?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How can I use Python and MySQL to generate a PDF?
- How can I use Python and MySQL to create a login system?
- How can I create a web application using Python and MySQL?
- How can I use Python to yield results from a MySQL database?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How can I use Python to interact with a MySQL database?
See more codes...