Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can create table using 'create as select' statement with sqlalchemy?

I have searched many tutors on how to create table with sqlalchemy:

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
engine = create_engine('sqlite:///college.db', echo = True)
meta = MetaData()

students = Table(
   'students', meta, 
   Column('id', Integer, primary_key = True), 
   Column('name', String), 
   Column('lastname', String),
)
meta.create_all(engine)

With create table as select structure,i can create a new table in psql console :

\c  dbname
create table newtable  as select * from dbtable;

It is simple to embed the create table as select command in psycopg2:

import psycopg2
conn = psycopg2.connect(database="dbname", user="postgres", password="xxxxxx", host="127.0.0.1")
sql_str = "create table newtable  as select * from dbtable;"
cur = conn.cursor()
cur.execute(sql_stsr)
conn.commit()

I want to embed it with sqlalchemy.After connecting the database with sqlalchemy:

from sqlalchemy import create_engine
create_engine("postgresql://postgres:localhost@postgres/dbname")

How can embed the create table newtable as select * from dbtable; in sqlalchemy then?

like image 796
showkey Avatar asked Feb 01 '26 06:02

showkey


1 Answers

You can simply do

with engine.begin() as conn:
    conn.exec_driver_sql("create table newtable  as select * from dbtable")
print('Table "newtable" created.')
like image 171
Gord Thompson Avatar answered Feb 03 '26 21:02

Gord Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!