2

I'm trying to save my pandas dataframe as a SQL file

I followed the documentation and tried

from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
df.to_sql('filename.sql', engine, chunksize=1000)

However, when I check the directory with os.listdir(), the file is not there

2
  • I don't think thats the purpose of the to_sql method, at least I never used it that way. I always use it to export to a database. Commented May 27, 2019 at 0:27
  • so after it's exported to a database, would I use a sqlalchemy function to save that database to a file? Commented May 27, 2019 at 0:28

1 Answer 1

3

The first argument you pass to to_sql should be the name of the table in your database, not the name of the file. Take a look at the docs.

Also, if you want to create a sqlite file, you should create an engine with a file database, not in-memory:

engine = sqlalchemy.create_engine("sqlite:///mydb.db")  # relative path to db
df.to_sql("my_table", engine)

Now there should be a file named mydb.db in the same directory where you run your application/script, with a table my_table containing the data in df.

Sign up to request clarification or add additional context in comments.

2 Comments

Say that I want to read the file into pandas later. Would I use engine = sqlalchemy.create_engine("sqlite:///mydb.db") , then with engine.connect() as conn, conn.begin():, then data = pd.read_sql_table('data', conn) ?
No, you can pass the engine directly to read_sql_table as the con argument. The docs say you can pass a SQLAlchemy connectable. So, this: data = pd.read_sql_table('data', engine).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.