Python 数据访问教程

Python 数据访问主页

Python MySQL

Python MySQL 简介 Python MySQL 数据库连接 Python MySQL 创建数据库 Python MySQL 创建表 Python MySQL 插入数据 Python MySQL 选择数据 Python MySQL Where 子句 Python MySQL 排序 Python MySQL 更新表 Python MySQL 删除数据 Python MySQL 删除表 Python MySQL Limit 子句 Python MySQL 连接 Python MySQL 游标对象

Python PostgreSQL

Python PostgreSQL 简介 Python PostgreSQL 数据库连接 Python PostgreSQL 创建数据库 Python PostgreSQL 创建表 Python PostgreSQL 插入数据 Python PostgreSQL 选择数据 Python PostgreSQL Where 子句 Python PostgreSQL 排序 Python PostgreSQL 更新表 Python PostgreSQL 删除数据 Python PostgreSQL 删除表 Python PostgreSQL Limit 子句 Python PostgreSQL 连接 Python PostgreSQL 游标对象

Python SQLite

Python SQLite 简介 Python SQLite 建立连接 Python SQLite 创建表 Python SQLite 插入数据 Python SQLite 选择数据 Python SQLite Where 子句 Python SQLite 排序 Python SQLite 更新表 Python SQLite 删除数据 Python SQLite 删除表 Python SQLite Limit 子句 Python SQLite 连接 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

#建立连接
conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1')

#使用 cursor() 方法创建游标对象
cursor = conn.cursor()

#如果数据库 MYDATABASE 已经存在,则将其删除。
cursor.execute("DROP database IF EXISTS MyDatabase")

#准备查询以创建数据库
sql = "CREATE database MYDATABASE";

#创建数据库
cursor.execute(sql)

#检索数据库列表
print("List of databases: ")
cursor.execute("SHOW DATABASES")
print(cursor.fetchall())

#关闭连接
conn.close()

输出

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