- Python 資料訪問教程
- Python 資料訪問 - 首頁
- Python MySQL
- Python MySQL - 簡介
- Python MySQL - 資料庫連線
- Python MySQL - 建立資料庫
- Python MySQL - 建立表
- Python MySQL - 插入資料
- Python MySQL - 選擇資料
- Python MySQL - Where 子句
- Python MySQL - Order By
- Python MySQL - 更新表
- Python MySQL - 刪除資料
- Python MySQL - 刪除表
- Python MySQL - Limit
- Python MySQL - Join
- Python MySQL - 遊標物件
- Python PostgreSQL
- Python PostgreSQL - 簡介
- Python PostgreSQL - 資料庫連線
- Python PostgreSQL - 建立資料庫
- Python PostgreSQL - 建立表
- Python PostgreSQL - 插入資料
- Python PostgreSQL - 選擇資料
- Python PostgreSQL - Where 子句
- Python PostgreSQL - Order By
- Python PostgreSQL - 更新表
- Python PostgreSQL - 刪除資料
- Python PostgreSQL - 刪除表
- Python PostgreSQL - Limit
- Python PostgreSQL - Join
- Python PostgreSQL - 遊標物件
- Python SQLite
- Python SQLite - 簡介
- Python SQLite - 建立連線
- Python SQLite - 建立表
- Python SQLite - 插入資料
- Python SQLite - 選擇資料
- Python SQLite - Where 子句
- Python SQLite - Order By
- Python SQLite - 更新表
- Python SQLite - 刪除資料
- Python SQLite - 刪除表
- Python SQLite - Limit
- Python SQLite - Join
- Python SQLite - 遊標物件
- Python MongoDB
- Python MongoDB - 簡介
- Python MongoDB - 建立資料庫
- Python MongoDB - 建立集合
- Python MongoDB - 插入文件
- Python MongoDB - 查詢
- Python MongoDB - 查詢
- Python MongoDB - 排序
- Python MongoDB - 刪除文件
- Python MongoDB - 刪除集合
- Python MongoDB - 更新
- Python MongoDB - Limit
- Python 資料訪問資源
- Python 資料訪問 - 快速指南
- Python 資料訪問 - 有用資源
- Python 資料訪問 - 討論
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',)]
廣告