top of page

Add a database to your python app with 5 lines of code

If you're building a python app and need a database, you can connect to a free cloud hosted Oracle Autonomous Database with 5 lines of code.

Building blocks

Let's create a simple Python app that generates random, secure passwords and saves them to a database. We’ll use a free Oracle Autonomous Database (ADB) for the database.

ADB’s are great if you need a database but don’t want to bother with database management, tuning, scaling, patching, upgrading, etc. as your app grows (see the full list of benefits here).

Simple to set up. Simple to use.

Want to understand how Oracle’s free cloud services work and set up your own autonomous database? Skip to the bottom for a quick guide here.

Let's build

First, we need our ADB connect string.

From our ADB home page, we'll need to set up our access control list. (I'll explain what this is below). If you've already enabled your access control list, you skip here.

From the ADB home page, select your database.

Once on the database page, click Edit next to the Access Control List.

Add your IP address by clicking Add my IP address, then save.

Now we can get our connect string for the python app.

Click Edit next to “Mutual TLS (mTLS) authentication: Required”

Uncheck the box and click save.

Once the changes are made, click Database connection.

Under the connection string section, switch to TLS authentication.

Note the connect string (we’ll use “*_high”).

Using whatever code editor/IDE you like, install the python-oracledb driver (assuming you already have python installed)

pip install oraceldb

Create a python file and add the following code:

import oracledb
import getpass
import random
import string

# Function to generate a password
def generate_password(length=30):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

# Function to save the name and password to the database
def save_name_and_password_to_db(connection, name, password):
        cursor = connection.cursor()
        # Create table if it doesn't exist
            CREATE TABLE IF NOT EXISTS passwords (
                name VARCHAR2(255),
                password VARCHAR2(255),
                CONSTRAINT passwords_pk PRIMARY KEY (id)

        # Insert the new name and password using parameterized query
        cursor.execute("INSERT INTO passwords (name, password) VALUES (:1, :2)", (name, password))
        print("Name and password saved to the database!")
    except oracledb.DatabaseError as e:
        print(f"Database error: {e}")

# Main function to interact with the user
def main():
    print("Welcome to the Password Generator!")

    # Get password for Oracle DB connection once
    pw = getpass.getpass("Enter your Oracle DB password: ")
        connection = oracledb.connect(
    except oracledb.DatabaseError as e:
        print(f"Failed to connect to the database: {e}")

    while True:
        # Get the name associated with the password
        name = input("Enter the name for the password: ").strip()
        if not name:
            print("Name cannot be empty.")

        # Generate a password
        length = input("Enter the desired password length (minimum 8, maximum 30): ")
            length = int(length)
            if length < 8:
                print("Password length should be at least 8 characters.")
            if length > 30:
                print("Password length should not exceed 30 characters.")
        except ValueError:
            print("Please enter a valid number.")
        password = generate_password(length)
        print(f"Generated Password was saved to the database")

        # Save the name and password to the database
        save_name_and_password_to_db(connection, name, password)

        more = input("Do you want to generate another password? (yes/no): ").strip().lower()
        if more != 'yes':

    # Close the connection when done

if __name__ == "__main__":

NOTE: your connection variable look like this:

        connection = oracledb.connect(
        cursor = connection.cursor()

You'll need to add your database user inside the user variable quotes and the connect string (that we found above) inside the quotes where it says dsn="your_connect_string" to connect to the database.

NOTE 2: The IF NOT EXISTS functionality will only work in Oracle database 23ai and forward. If you haven't upgraded to the database you'll need to change the code above.

Once you execute the app, you need to give the password for your database user and … just like that, we’ve got a secure password generator that saves passwords to a free Oracle Cloud Autonomous Database.

Supporting info

Whats an access control list?

ADB uses mTLS and TLS for database connections. mTLS requires both the client and server to verify each other using secret keys. TLS only requires the server to verify its key, reducing complexity but still maintaining security through Access Control Lists (ACLs).

Is TLS less secure tha mTLS

That depends. While mTLS provides an additional layer of security by requiring both parties to exchange credentials, TLS can still be highly secure. For example, to enable TLS on an ADB instance with an exposed public endpoint, you must set up an Access Control List (ACL). The ACL functions as an “allow” list, restricting access to only the specified IP addresses or Virtual Cloud Networks (VCNs) included in it.

How does Oracle Clouds free service work?

Oracle’s Cloud offers a free access to cloud resources. The free cloud account has with two parts:

  1. Free Tier

  2. Always free

Free Tier - When you first create your cloud account, you're given $300 worth of cloud resources that work for 30 days. It’s a trial. You can test out difference services on Oracles cloud BUT after the 30 days are over, if you dont upgrade your account, any of the resources you created (with your $300 worth of free credit) will be stoped. You would need to MANUALLY upgrade. If you dont upgrade you wont be charged. Anything you created with your credits are reclaimed by Oracle unless you upgrade your account.

Always Free - After the 30 days of the trial your account is what oracle calls “always free” here you can only create resources that are completely free. There’s no way to accidentally create a paid service. You would need to manually upgrade your account before you would be charged. Check out this for a list of free cloud resources you can create with your Oracle Cloud account.

But why do I need to give my credit card if it's free?

The story i was told when I asked was "Prior to the credit card requirement, crypto miners would use the $300 worth of cloud credits to mine for bitcoin and repeatedly create new accounts once they’d spent the money. Adding the credit card requirement helped stop that" (I liked the answer so I never verified if it was actually true).

- Killian


bottom of page