Ask Your Question
3

How can I use SQLAlchemy to create and update PostgreSQL variables and then return the data using Pandas?

asked 2023-05-15 23:57:03 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-16 00:20:02 +0000

pufferfish gravatar image

To create and update PostgreSQL variables using SQLAlchemy, you can use the text method to execute raw SQL queries. Here's an example of how you can create and update variables:

from sqlalchemy import create_engine, text
import pandas as pd

# create database connection
engine = create_engine('postgresql://username:password@host:port/database')

# create variables
engine.execute(text("CREATE TEMP TABLE my_var AS SELECT 1 as val;"))
engine.execute(text("UPDATE my_var SET val = 2;"))

# read data into pandas dataframe
df = pd.read_sql_query("SELECT * FROM my_var", engine)

# display dataframe
print(df)

In the above code, we first create a database connection using SQLAlchemy's create_engine function. Then, we use the text method to execute raw SQL queries, CREATE TEMP TABLE my_var AS SELECT 1 as val; to create a variable name my_var with a column value of 1 and UPDATE my_var SET val = 2; to update the variable value to 2. Finally, we use Pandas' read_sql_query method to read the data into a dataframe, which we then display.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-15 23:57:03 +0000

Seen: 11 times

Last updated: May 16 '23