📜  Python MySQL创建新数据库

📅  最后修改于: 2020-10-25 03:39:35             🧑  作者: Mango

创建新数据库

在本教程的这一部分中,我们将创建新的数据库PythonDB。

获取现有数据库列表

通过使用以下MySQL查询,我们可以获得所有数据库的列表。

>  show databases;

import mysql.connector

#Create the connection object 
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")

#creating the cursor object
cur = myconn.cursor()

try:
    dbs = cur.execute("show databases")
except:
    myconn.rollback()
for x in cur:
    print(x)
myconn.close()

输出:

('EmployeeDB',)
('Test',)
('TestDB',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mysql',)
('performance_schema',)
('testDB',)

创建新数据库

可以使用以下SQL查询创建新数据库。

>  create database   

import mysql.connector

#Create the connection object 
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")

#creating the cursor object
cur = myconn.cursor()

try:
    #creating a new database
    cur.execute("create database PythonDB2")

    #getting the list of all the databases which will now include the new database PythonDB
    dbs = cur.execute("show databases")
    
except:
    myconn.rollback()

for x in cur:
        print(x)
        
myconn.close()

输出:

('EmployeeDB',)
('PythonDB',)
('Test',)
('TestDB',)
('anshika',)
('information_schema',)
('javatpoint',)
('javatpoint1',)
('mydb',)
('mydb1',)
('mysql',)
('performance_schema',)
('testDB',)