Python 3 无法检查数据库是不是存在并创建它
Posted
技术标签:
【中文标题】Python 3 无法检查数据库是不是存在并创建它【英文标题】:Python 3 failed to check whether the database exists and create itPython 3 无法检查数据库是否存在并创建它 【发布时间】:2021-01-24 13:15:21 【问题描述】:我是 python 初学者。我想使用 Python 3 检查 SQL 服务器上的 test2
数据库。如果它不存在,我将创建它。但是发现报错了,不知道怎么办?
python 代码:
import pymssql
def conn():
ret = pymssql.connect(host='DESKTOP-4CDQOMR', user = 'sa', password = '123456')
if ret:
print("connect successfully!")
else:
print("connect failed!")
return ret
if __name__ == '__main__':
conn = conn()
if conn:
cursor = conn.cursor()
sql = "if not exist (select * from sys.databases where name = 'test2')"
conn.autocommit(True)
cursor.execute(sql)
conn.autocommit(False)
conn.close()
错误信息:
---------------------------------------------------------------------------
MSSQLDatabaseException Traceback (most recent call last)
src\pymssql.pyx in pymssql.Cursor.execute()
src\_mssql.pyx in _mssql.MSSQLConnection.execute_query()
src\_mssql.pyx in _mssql.MSSQLConnection.execute_query()
src\_mssql.pyx in _mssql.MSSQLConnection.format_and_run_query()
src\_mssql.pyx in _mssql.check_cancel_and_raise()
src\_mssql.pyx in _mssql.maybe_raise_MSSQLDatabaseException()
MSSQLDatabaseException: (156, b"Incorrect syntax near the keyword 'select'.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\nDB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
During handling of the above exception, another exception occurred:
OperationalError Traceback (most recent call last)
F:\jupyter\connect.py in <module>
20 sql = "if not exist (select * from sys.databases where name = 'test2')"
21 conn.autocommit(True)
---> 22 cursor.execute(sql)
23 conn.autocommit(False)
24 conn.close()
src\pymssql.pyx in pymssql.Cursor.execute()
OperationalError: (156, b"Incorrect syntax near the keyword 'select'.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\nDB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
【问题讨论】:
***.com/questions/167576/… 可能有帮助 @Leo Arad 对不起,我还是找不到我想要的答案,因为它主要讨论的是表而不是数据库 【参考方案1】:我已经通过修改以下代码解决了我的问题:
sql = "if not exist (select * from sys.databases where name = 'test2')"
到
sql = "if not exists (select * from sys.databases where name = 'test2') begin create database test2 end"
【讨论】:
【参考方案2】:我没有安装 MS SQL Server 来测试,但是
if not exist (select * from sys.databases where name = 'test2')
在我看来这不是有效的 SQL。
也许你想做这样的事情:
cur = conn.cursor()
# Check if the database already exists.
cur.execute("""SELECT COUNT(*) FROM sys.databases WHERE name = 'test2'""")
res = cur.fetchone()[0]
if res == 0:
conn.autocommit(True)
cur.execute("""CREATE DATABASE test2""")
conn.autocommit(False)
另一种方法可能是尝试直接创建数据库,并在异常已存在时捕获该异常。如果在您获取计数和发送 create 语句之间可能会有其他人创建数据库,那么这是一种更好的方法。
import sys
cur = conn.cursor()
conn.autocommit(True)
try:
cur.execute("""CREATE DATABASE test2""")
except Exception as ex:
# Rollback is probably unnecessary
conn.rollback()
print('Failed to create the database because', ex, file=sys.stderr)
finally:
conn.autocommit(False)
conn.close()
【讨论】:
【参考方案3】:您好,希望下面的代码对您有所帮助!
import mysql.connector
DB_NAME = "test2"
client = mysql.connector.connect(host = "127.0.0.1",
user = "admin",
passwd = "password")
mycursor = client.cursor()
mycursor.execute("SHOW DATABASES")
if DB_NAME in mycursor: print("Database exists :)")
else :
print(f"Database DB_NAME doesn't exist, creating now....")
mycursor.execute("CREATE DATABASE firstdatabase")
print(f"Database DB_NAME created!")
【讨论】:
问题是关于 MS -SQL Server,而不是 MySQL。以上是关于Python 3 无法检查数据库是不是存在并创建它的主要内容,如果未能解决你的问题,请参考以下文章
如何检查 SQL Server CE 3.5 中是不是存在表
Python 检查目录是不是存在,然后在必要时创建它并将图形保存到新目录? [复制]