BetterCallMe
BetterCallMe

Reputation: 768

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?

Upvotes: 5

Views: 4408

Answers (2)

okayama-taro
okayama-taro

Reputation: 65

you could do it, by "pl.read_database", not by "pl.read_sql".

I could read sqlite3 db using polars by this way. From polars website: https://docs.pola.rs/py-polars/html/reference/api/polars.read_database.html#polars.read_database

import sqlite3
import polars as pl

dbname = "test.db"     # sqlite3 db file path
conn = sqlite3.connect(dbname)

df = pl.read_database(
    query="SELECT * FROM test_table", 
    connection=user_conn,
    schema_overrides={"normalised_score": pl.UInt8}, 
)  

I could get sqlite3 db.table.

Upvotes: 2

Nedim Ramic
Nedim Ramic

Reputation: 179

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)

Upvotes: 6

Related Questions