Python MySQL - 建立資料庫



您可以使用 CREATE DATABASE 查詢在 MYSQL 中建立資料庫。

語法

以下是 CREATE DATABASE 查詢的語法:

CREATE DATABASE name_of_the_database

示例

以下語句在 MySQL 中建立了一個名為 mydb 的資料庫:

mysql> CREATE DATABASE mydb;
Query OK, 1 row affected (0.04 sec)

如果您使用 SHOW DATABASES 語句檢視資料庫列表,您可以在其中看到新建立的資料庫,如下所示:

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| logging            |
| mydatabase         |
| mydb               |
| performance_schema |
| students           |
| sys                |
+--------------------+
26 rows in set (0.15 sec)

使用 python 在 MySQL 中建立資料庫

在與 MySQL 建立連線後,要操作其中的資料,您需要連線到一個數據庫。您可以連線到現有的資料庫,或者建立您自己的資料庫。

您需要特殊的許可權才能建立或刪除 MySQL 資料庫。因此,如果您有權訪問 root 使用者,則可以建立任何資料庫。

示例

以下示例與 MYSQL 建立連線並在其中建立一個數據庫。

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()

輸出

List of databases:
[('information_schema',), ('dbbug61332',), ('details',), ('exampledatabase',), ('mydatabase',), ('mydb',), ('mysql',), ('performance_schema',)]
廣告

© . All rights reserved.