MySQL创建一个表完整过程怎么写

2023-12-15 10:57:03 网络知识 悟空

创建一个表的完整过程包括以下几个步骤:

连接到 MySQL 数据库。

import mysql.connector

# 创建数据库连接
cnx = mysql.connector.connect(user='your_username', password='your_password',
                              host='localhost', database='your_database')

# 创建游标对象
cursor = cnx.cursor()

    编写 SQL 建表语句。

    # 创建表的 SQL 语句
    create_table_sql = """
    CREATE TABLE your_table (
      id int(11) NOT NULL AUTO_INCREMENT,
      name varchar(100) NOT NULL,
      age int(11) NOT NULL,
      email varchar(100) NOT NULL,
      PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
    """
    
    

      执行建表语句。

      # 执行建表语句
      cursor.execute(create_table_sql)
      

        提交事务。

        # 提交事务
        cnx.commit()
        

          关闭游标和数据库连接。

          # 关闭游标
          cursor.close()
          
          # 关闭数据库连接
          cnx.close()
          

          以上是使用 Python 的 MySQL Connector 进行 MySQL 表的创建过程。在实际应用中,你需要根据自己的需求和具体环境来自定义建表语句、数据库连接参数等。

发表评论: