Python MySQL create table


chapter


Create a table

To create a table in MySQL, use the "CREATE TABLE" statement.

Be sure to specify when you create a database connection

Examples

Create a table called "customers" are:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

If the above is not being given code execution, then you have successfully created a table.

Check the table exists

You can use "SHOW TABLES" statement to list all tables in the database to check whether there is a table:

Examples

Returns all tables in the database:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW TABLES")

for x in mycursor:
  print(x)

Primary key

When you create a table, you should create a primary key field. Primary key uniquely identifies a row.

You can use the statement "INT AUTO_INCREMENT PRIMARY KEY" to create a primary key, it will create an auto-incremented ID (from the beginning, each record increase 1) as the primary key.

Examples

When you create a table, and create a primary key:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")

If the table already exists, you can create a primary key using ALTER TABLE keyword:

Examples

Create a primary key on an existing table:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")

Guess you like

Origin www.cnblogs.com/jinbuqi/p/11588804.html