【发布时间】:2020-11-25 02:05:26
【问题描述】:
我正在学习 PyMySQL。如果我问了什么愚蠢的事情,请原谅我。
我希望创建一个可以自动判断数据库是否存在的脚本。如果没有,将创建一个。如果存在,将什么都不做。下面是我的脚本。我无法创建数据库。任何建议将不胜感激。
import mysql.connector as sql
from mysql.connector import Error
import os
#create a database
db_name = input("Input database name:")
db_name = db_name.strip()
try:
db = sql.connect(host='localhost',
user='user',
password='SQLpractice',
)
cursor = db.cursor()
# cursor.execute("flg = False if NOT EXISTS Electronics;")
if os.path.isfile(db_name):
flg = True
print(db_name, " exists. Nothing to do.\n")
else:
flg = False
print(db_name," does not exist. Will create it if no errors happened.\n")
cursor.execute("CREATE DATABASE IF NOT EXISTS %s",(db_name) )
print("Show database below.\n")
cursor.execute("SHOW DATABASES")
except Error as e:
print("Error, cannot create database, database exists or something else wrong.\n")
finally:
if flg:
print("Created database.\n")
else:
print("No database created. Database exists or something wrong (flg=",flg,").\n")
【问题讨论】:
-
服务器返回的错误是什么?
-
没有错误信息,但是没有创建数据库。
标签: python python-3.x database pymysql