📜  Python MySQL – 创建数据库

📅  最后修改于: 2022-05-13 01:55:34.040000             🧑  作者: Mango

Python MySQL – 创建数据库

Python数据库 API(应用程序接口)是标准Python的数据库接口。大多数Python数据库接口都遵守此标准。 Python数据库支持各种数据库服务器,例如 MySQL、GadFly、mSQL、PostgreSQL、Microsoft SQL Server 2000、Informix、Interbase、Oracle、Sybase 等。要从Python连接 MySQL 数据库服务器,我们需要导入 mysql.connector界面。
句法:

CREATE DATABASE DATABASE_NAME

例子:

Python
# importing required libraries
import mysql.connector
 
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="gfg"
)
 
# preparing a cursor object
cursorObject = dataBase.cursor()
 
# creating database
cursorObject.execute("CREATE DATABASE geeks4geeks")


Python
# importing required library
import mysql.connector
 
# connecting to the database
dataBase = mysql.connector.connect(
                     host = "localhost",
                     user = "user",
                     passwd = "gfg",
                     database = "geeks4geeks" ) 
 
# preparing a cursor object
cursorObject = dataBase.cursor()
 
# creating table 
studentRecord = """CREATE TABLE STUDENT (
                   NAME  VARCHAR(20) NOT NULL,
                   BRANCH VARCHAR(50),
                   ROLL INT NOT NULL,
                   SECTION VARCHAR(5),
                   AGE INT
                   )"""
 
# table created
cursorObject.execute(studentRecord) 
 
# disconnecting from server
dataBase.close()


输出:

python-mysql-create-db

上面的程序演示了 MySQL 数据库 geeks4geeks 的创建,其中主机名是 localhost,用户名是 user,密码是 gfg。
假设我们要在数据库中创建一个表,那么我们需要连接到一个数据库。下面是在上述程序中创建的 geeks4geeks 数据库中创建表的程序。

Python

# importing required library
import mysql.connector
 
# connecting to the database
dataBase = mysql.connector.connect(
                     host = "localhost",
                     user = "user",
                     passwd = "gfg",
                     database = "geeks4geeks" ) 
 
# preparing a cursor object
cursorObject = dataBase.cursor()
 
# creating table 
studentRecord = """CREATE TABLE STUDENT (
                   NAME  VARCHAR(20) NOT NULL,
                   BRANCH VARCHAR(50),
                   ROLL INT NOT NULL,
                   SECTION VARCHAR(5),
                   AGE INT
                   )"""
 
# table created
cursorObject.execute(studentRecord) 
 
# disconnecting from server
dataBase.close()

输出:

Python-MYSQL-CREATE-DB1