Can someone please check my syntax

Hi,

I am trying to create a Lambda inside AWS that will add a record to the mysql database. Connection is fine & I have a select statement working.

Ive turned my attention to an insert statement & this is my attempt.

def lambda_handler(event, context):
    conn = None
    try:
        conn = pymysql.connect(
            database=db_creds["dbname"],
            host=db_creds["host"],
            user=db_creds["username"],
            password=db_creds["password"],
            port=db_creds["port"],
            charset="utf8mb4",
            connect_timeout=20,
            cursorclass=pymysql.cursors.DictCursor,
        )
        category = event['Category']
        with conn.cursor() as cursor:

            sql = "INSERT INTO `tbl_Categories_au` (`Category`, `Approved`) VALUES (%s, 1)"
            cursor.execute(sql, (category))

        msg = "Category added successfully"
        status = 200
    except:
        msg = "Connection failed"
        status = 500
    finally:
        if conn is not None:
            conn.close()

    return {
        "statusCode": status,
        "headers": {"Access-Control-Allow-Origin": "*"},
        "body": msg,
    }

Am getting error 500 connection failed but I know the credentials are right.

Thanks in advance

Todd

Try removing the try clause first. It’s going to fail, and the exception type and message should give you a clue.

Also note that bare except statements are discouraged since they catch any exception, including KeyboardInterrupt, preventing you from stopping the program with Ctrl-C. If you want to catch any error, use except Exception:. Better yet is to identify the precise exception type that can happen under normal circumstances and narrow the except to that (e.g., except DataError:; see the full exception hierarchy related to databases in PEP 249).

1 Like