<@ULVA73B9P> I have a DatabaseCredentials block....
# marvin-in-the-wild
c
@Marvin I have a DatabaseCredentials block. How do I use it in a flow to operate on a SQL table?
m
It seems the tool for getting a code example did not provide a relevant example for using a
DatabaseCredentials
block. Let me guide you through an appropriate approach based on Prefect documentation excerpts I found using
multi_tool_use.parallel
. For your specific use-case of operating on a SQL table within a flow, here's an example using Prefect Snowflake integration, but the same logic applies to any SQL database using the corresponding Prefect integration. When using the
SnowflakeConnector
block (you would use your corresponding database block):
Copy code
python
from prefect_snowflake.database import SnowflakeConnector

with SnowflakeConnector.load("BLOCK_NAME") as conn:
    conn.execute("CREATE TABLE IF NOT EXISTS customers (name varchar, address varchar);")
    conn.execute_many(
        "INSERT INTO customers (name, address) VALUES (%(name)s, %(address)s);",
        seq_of_parameters=[
            {"name": "Ford", "address": "Highway 42"},
            {"name": "Unknown", "address": "Space"},
            {"name": "Marvin", "address": "Heart of Gold"},
        ],
    )
    results = conn.fetch_all(
        "SELECT * FROM customers WHERE address = %(address)s",
        parameters={"address": "Space"}
    )
    print(results)
For SQLAlchemy with
DatabaseCredentials
block, you would create an authenticated engine to query the database:
Copy code
python
from prefect import flow
from prefect_sqlalchemy import DatabaseCredentials, AsyncDriver

@flow
def sqlalchemy_credentials_flow():
    sqlalchemy_credentials = DatabaseCredentials(
        driver=AsyncDriver.POSTGRESQL_ASYNCPG,
        username="prefect_user",
        password="prefect_password",
        # Add all other required connection parameters
    )
    # Use sqlalchemy_credentials to create engine and connect to the database
Here,
sqlalchemy_credentials
will be the object you use to get a connection engine to your database. Within your flow, you can then use this connection to perform SQL operations such as creating tables, inserting data, and querying information. For more details and to tailor the code to your specific database, please refer to the Snowflake Connector documentation and SQLAlchemy Credentials documentation. Remember to use the corresponding Prefect library for your database and replace "BLOCK_NAME" with the name of your specific
DatabaseCredentials
block.