Skip to content

Commit 450291a

Browse files
authored
Merge pull request techiescamp#2 from dv-sharma/patch-1
Create awsrdsmysqlp.py
2 parents 4909d07 + d97c2f2 commit 450291a

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

awsrdsmysqlp.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import boto3
2+
import json
3+
import mysql.connector
4+
import tabulate
5+
6+
# Initialize AWS Secrets Manager client
7+
secrets_manager = boto3.client('secretsmanager')
8+
db_host = "DB_HOST"
9+
10+
def get_secretvalue():
11+
secret_name = secrets_manager.get_secret_value(SecretId='YOUR_SECRET_ARN')
12+
secret_dict = json.loads(secret_name['SecretString'])
13+
db_username = secret_dict['username']
14+
db_password = secret_dict['password']
15+
return db_username, db_password
16+
17+
def execute_query(db_name, query):
18+
db_username, db_password = get_secretvalue()
19+
20+
for db in db_name:
21+
try:
22+
connection = mysql.connector.connect(
23+
host=db_host,
24+
user=db_username,
25+
password=db_password,
26+
database=db
27+
)
28+
cursor = connection.cursor()
29+
cursor.execute(query)
30+
result = cursor.fetchall()
31+
row_count = cursor.rowcount
32+
33+
if query.upper().startswith(("SELECT", "SHOW", "DESCRIBE")):
34+
if result:
35+
header = [column_name[0] for column_name in cursor.description]
36+
table_output = [header] + list(result)
37+
print(f"Running query on: {db}")
38+
print(tabulate.tabulate(table_output, tablefmt="pipe"))
39+
else:
40+
print("Empty result")
41+
else:
42+
connection.commit()
43+
print(f"{row_count} rows affected in {db}")
44+
45+
except Exception as e:
46+
print("Error:", e)
47+
finally:
48+
if 'connection' in locals():
49+
connection.close()
50+
51+
db_names = input("Enter the DB names followed by space:").split()
52+
query = input("Enter the query:")
53+
execute_query(db_names, query)

0 commit comments

Comments
 (0)