python-mysqlHow do I create a primary key in MySQL using Python?
Creating a primary key in MySQL using Python is a simple process. The following example code will create a table called ‘students’ with a primary key called ‘id’:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
This code will create a table called ‘students’ with a primary key called ‘id’. The ‘id’ column is set to auto-increment, which means it will automatically increment each time a new record is inserted.
The code consists of the following parts:
import mysql.connector
: This imports the mysql.connector library which is used to connect to the MySQL database.mydb = mysql.connector.connect(host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase")
: This establishes a connection to the MySQL database.mycursor = mydb.cursor()
: This creates a cursor object which is used to execute queries.mycursor.execute("CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
: This creates a table called ‘students’ with a primary key called ‘id’, and two additional columns called ‘name’ and ‘address’.
No output will be displayed when the code is run.
Helpful links
More of Python Mysql
- How can I connect Python to a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How can I use Yum to install the MySQLdb Python module?
- How do I check the version of MySQL I am using with Python?
- How can I retrieve unread results from a MySQL database using Python?
- How can I use Python to insert a timestamp into a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to connect to a MySQL database using XAMPP?
- How do I connect to a MySQL database using XAMPP and Python?
- How do I update values in a MySQL database using Python?
See more codes...