[英]How to drop table and recreate in amazon RDS with Elasticbeanstalk?
我在亞馬遜上的數據庫目前只有很少的數據(我正在制作一個 web 應用程序,但它仍在開發中),我想刪除它,更改架構,然后重新備份。 過去幾次我這樣做了,我已經完全重新創建了我的 elasticbeanstalk 應用程序,但似乎有更好的方法。 在我的本地機器上,我將執行以下步驟:
我可以在亞馬遜上做這樣的事情來刪除我的數據庫並將其重新聯機而不刪除整個應用程序嗎? 當我剛剛嘗試刪除 RDS 實例並創建一個新實例時,我遇到了 elasticbeanstalk 的問題。
完成此操作的最簡單方法是SSH到RDS DB擁有的EC2實例之一,然后從那里連接到DB。 確保您的python腳本可以讀取您的應用配置以訪問已配置的數據庫,或為數據庫主機名添加參數。 要刪除和創建數據庫,您只需添加必要的參數即可連接到數據庫。 例如:
$ createdb -h <RDS endpoint> -U <user> -W ebdb
您還可以在數據庫為空時創建RDS快照,並使用RDS實例操作Restore to Time in Time或Migrate Latest Snapshot 。
我遇到了同樣的問題並想出了一個解決方法。 在您的 python 代碼中,只需在下次部署您的應用程序時添加並運行以下方法:
對於 SQLALCHEMY 版本 2.0 之后
from sqlalchemy import create_engine, text
tables = ["table1_name", "table2_name"] # the names of the tables you want to delte
engine = create_engine("sqlite:///example.db") # here you create your engine
def delete_tables(tables):
for table in tables:
sql = text(f"DROP TABLE IF EXISTS {table} CASCADE;") # CASCADE deltes the tables even if they had some connections to other tables
with engine.connect() as connection:
with connection.begin():
connection.execute(sql)
delete_tables(tables) # Comment this line out after running it once.
對於版本 2 之前的 SQLALCHEMY(我猜)
def delete_tables(tables):
for table in tables:
engine.execute(f"DROP TABLE IF EXISTS {table} CASCADE;")
delete_tables(tables) # Comment this line out after running it once.
部署並運行此代碼 1 次后,所有表都將被刪除。
重要提示:之后刪除或注釋掉此代碼,否則每次將代碼部署到 AWS 時都會刪除所有表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.