Get the App
SLTechnology News&Howtos  ›  Development  › 

How to set the primary key in the database

Shulou Source: shulou.com Published: 2022-06-01 01:33:20 10月04日 Update

This article mainly introduces the relevant knowledge of "how to set the primary key in the database". The editor shows you the operation process through the actual case, and the operation method is simple, fast and practical. I hope this article "how to set the primary key in the database" can help you solve the problem.

Primary key settin

When we create a table, we usually set a primary key (PRIMARY KEY). We can use the "INT AUTO_INCREMENT PRIMARY KEY" statement to create a primary key, with a starting value of 1, incremented step by step.

If our table has been created, we need to use ALTER TABLE to add the primary key to the table:

Demo_mysql_test.py:

Add a primary key to the sites table.

Import mysql.connector

Mydb = mysql.connector.connect (

Host= "localhost"

User= "root"

Passwd= "123456"

Database= "runoob_db"

)

Mycursor = mydb.cursor ()

Mycursor.execute ("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

If you haven't created the sites table yet, you can create it directly using the following code.

Demo_mysql_test.py:

Create a primary key for the table.

Import mysql.connector

Mydb = mysql.connector.connect (

Host= "localhost"

User= "root"

Passwd= "123456"

Database= "runoob_db"

)

Mycursor = mydb.cursor ()

Mycursor.execute ("CREATE TABLE sites (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR (255), url VARCHAR (255)")

This is the end of the content about "how to set the primary key in the database". Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Data database knowledge industry different practical code content practicality practice article method time more case knowledge point article sentence information information channel Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Huawei Redmi Shulou Information Apple