Python Data Access 简明教程
Python MySQL - Create Database
你可以在 MYSQL 中使用 CREATE DATABASE 查询创建一个数据库。
You can create a database in MYSQL using the CREATE DATABASE query.
Syntax
以下是 CREATE DATABASE 查询的语法:
Following is the syntax of the CREATE DATABASE query −
CREATE DATABASE name_of_the_database
Example
以下语句在 MySQL 中创建一个名为 mydb 的数据库:
Following statement creates a database with name mydb in MySQL −
mysql> CREATE DATABASE mydb;
Query OK, 1 row affected (0.04 sec)
如果你使用 SHOW DATABASES 语句查看数据库列表,那么你可以看到其中新创建的数据库,如下所示:
If you observe the list of databases using the SHOW DATABASES statement, you can observe the newly created database in it as shown below −
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| logging |
| mydatabase |
| mydb |
| performance_schema |
| students |
| sys |
+--------------------+
26 rows in set (0.15 sec)
Creating a database in MySQL using python
在与 MySQL 建立连接后,你要在其中处理数据就需要连接到一个数据库。你可以连接到现有的数据库或创建你自己的数据库。
After establishing connection with MySQL, to manipulate data in it you need to connect to a database. You can connect to an existing database or, create your own.
你要创建或删除 MySQL 数据库,需要具有特殊权限。因此,如果你可以访问 root 用户,则你可以创建任何数据库。
You would need special privileges to create or to delete a MySQL database. So if you have access to the root user, you can create any database.
Example
以下示例建立与 MYSQL 的连接并在其中创建一个数据库。
Following example establishes connection with MYSQL and creates a database in it.
import mysql.connector
#establishing the connection
conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Doping database MYDATABASE if already exists.
cursor.execute("DROP database IF EXISTS MyDatabase")
#Preparing query to create a database
sql = "CREATE database MYDATABASE";
#Creating a database
cursor.execute(sql)
#Retrieving the list of databases
print("List of databases: ")
cursor.execute("SHOW DATABASES")
print(cursor.fetchall())
#Closing the connection
conn.close()