如何使用 sqlalchemy 搜索数据库的存在 [英] how to search for the existence of a database with sqlalchemy
本文介绍了如何使用 sqlalchemy 搜索数据库的存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要用 python sqlalchemy 编写一个脚本来搜索数据库是否存在,如果数据库存在,它应该查询数据库,否则创建数据库和表.
I need to write a script with python sqlalchemy that searchs if a database exist, if the database exists it should query the database else create database and tables.
伪代码:
if db exists cursor.execute(sql)
else
create db test;
create tables;
insert data;
推荐答案
您可以使用 sqlalchemy.engine.base.Engine.connect()
方法,该方法会引发 OperationalError
如果数据库不存在.
You can use the sqlalchemy.engine.base.Engine.connect()
method, which will raise a OperationalError
if the database does not exist.
import sqlalchemy as sqla
db = sqla.create_engine(database_uri)
try:
db.connect()
db.execute(sql)
except OperationalError:
# Switch database component of the uri
default_database_uri = os.path.join(os.path.dirname(
str(db.engine.url)), 'mysql')
db = sqla.create_engine(default_database_uri)
# Create your missing database/tables/data here
# ...
这篇关于如何使用 sqlalchemy 搜索数据库的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文