Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to set the primary key in the database

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report