How to Create a Primary Key in Python?

Estimated read time 2 min read

In Python, you can create a primary key for a table in a relational database using SQL commands executed through a database API, such as sqlite3, mysql-connector, or psycopg2 depending on your specific database. Here’s an example code snippet using sqlite3:

import sqlite3

# connect to database
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()

# create table with primary key
cursor.execute('''CREATE TABLE mytable
                  (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

# insert data into table
cursor.execute("INSERT INTO mytable (name, age) VALUES (?, ?)", ("Alice", 25))
cursor.execute("INSERT INTO mytable (name, age) VALUES (?, ?)", ("Bob", 30))
cursor.execute("INSERT INTO mytable (name, age) VALUES (?, ?)", ("Charlie", 35))
conn.commit()

# close database connection
conn.close()

In this example, we first import the sqlite3 module and create a database connection using the connect() function. We also create a cursor object to execute SQL commands.

We create a new table called mytable with three columns: id, name, and age. We specify that the id column is a primary key using the PRIMARY KEY constraint.

We insert some sample data into the table using the INSERT INTO command, and commit the changes to the database using the commit() method of the connection object.

Finally, we close the database connection using the close() method.

You can modify this code to work with your specific database and table schema, and use other SQL commands to manipulate the data in the table.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply