Python 创建表
- 上一页 MySQL Create Database
- 下一页 MySQL Insert
创建表
如需在 MySQL 中创建表,请使用 "CREATE TABLE" 语句。
请确保在创建连接时定义数据库的名称。
实例
创建表 "customers":
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
如果执行上面的代码没有错误,那么您现在已经成功创建了一个表。
ການກວດຫາຕາມຫຼືບໍ່
ທ່ານສາມາດໃຊ້ຄຳສັ່ງ "SHOW TABLES" ເພື່ອລາຍງາຍທຸກຕາມຂອງຖານຂໍ້ມູນເພື່ອກວດຫາວ່າມີຕາມຫຼືບໍ່:
实例
ການຫາຄູ່ມີຂອງຖານຂໍ້ມູນຂອງລະບົບ:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("SHOW TABLES") for x in mycursor: print(x)
ພາຍສີກະກັບສະຖານທີ່
ຕອນທີ່ສ້າງຕາມກະກັບການສ້າງວັດຖຸທີ່ມີພຽງພໍບັນດາການຄວາມຈິງ.
ສາມາດເຮັດໄດ້ດ້ວຍການກໍານົດ PRIMARY KEY.
我们使用语句 "INT AUTO_INCREMENT PRIMARY KEY",它将为每条记录插入唯一的编号。从 1 开始,每个记录递增 1。
实例
创建表时创建主键:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
如果表已存在,请使用 ALTER TABLE 关键字:
实例
在已有的表上创建主键:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
- 上一页 MySQL Create Database
- 下一页 MySQL Insert