pythonsqlitepython-polars

How to read a SQLite database file using polars package in Python


I want to read a SQLite database file (database.sqlite) using polars package. I tried following unsuccessfully:

import sqlite3
import polars as pl

conn = sqlite3.connect('database.sqlite')
df = pl.read_sql("SELECT * from table_name", conn)

print(df)

Getting following error:

AttributeError: 'sqlite3.Connection' object has no attribute 'split'

Any suggestions?


Solution

  • From the docs, you can see pl.read_sql accepts connection string as a param, and you are sending the object sqlite3.Connection, and that's why you get that message.

    You should first generate the connection string, which is url for your db

    db_path = 'database.sqlite'
    connection_string = 'sqlite://' + db_path
    

    And after that, you can type the updated next line, which gave you problems:

    df = pl.read_sql("SELECT * from table_name", connection_string)