Created
December 5, 2023 22:06
-
-
Save kennethphough/819f7f3342cac88533dc3537c6680b13 to your computer and use it in GitHub Desktop.
Python Lambda script for connecting to a RDS MySQL instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import pymysql | |
import os | |
def lambda_handler(event, context): | |
# Establish a connecto the the MySQL database | |
connection = pymysql.connect(host=os.environ['db_host'], user=os.environ['db_username'], password=os.environ['db_password'], database=os.environ['db_name']) | |
# Add a new user and print the updated user list | |
add_new_user(connection, 'JohnDoe', 'johndoe@example.com') | |
print_user_list(connection) | |
# Close the connection | |
connection.close() | |
return { | |
'statusCode': 200, | |
'body': json.dumps('Hello from Lambda!') | |
} | |
# Function to add a new user | |
def add_new_user(connection, username, email): | |
try: | |
with connection.cursor() as cursor: | |
sql = "INSERT INTO users (username, email) VALUES (%s, %s)" | |
cursor.execute(sql, (username, email)) | |
connection.commit() | |
print("New user added successfully!") | |
except Exception as e: | |
connection.rollback() | |
print(f"Error adding user: {e}") | |
# Function to retrieve and print the user list | |
def print_user_list(connection): | |
try: | |
with connection.cursor() as cursor: | |
cursor = connection.cursor(pymysql.cursors.DictCursor) # Using DictCursor | |
sql = "SELECT * FROM users" | |
cursor.execute(sql) | |
users = cursor.fetchall() | |
print("List of users:") | |
for user in users: | |
print(f"ID: {user['id']} | Username: {user['username']} | Email: {user['email']} | Created At: {user['created_at']}") | |
except Exception as e: | |
print(f"Error retrieving user list: {e}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment