In this Python quickstart we will learn how to:

  • Retrieve database credentials
  • Install the libSQL package
  • Connect to a Turso database
  • Execute a query using SQL
  • Sync changes to local database (optional)
1

Retrieve database credentials

You will need an existing database to continue. If you don’t have one, create one.

Get the database URL:

turso db show --url <database-name>

Get the database authentication token:

turso db tokens create <database-name>

Assign credentials to the environment variables inside .env.

TURSO_DATABASE_URL=
TURSO_AUTH_TOKEN=
You will want to store these as environment variables.
2

Install

First begin by adding libSQL to your project:

pip install libsql-experimental
3

Connect

Then import the package:

import libsql_experimental as libsql

Now connect to your local or remote database using the libSQL connector:

4

Execute

You can execute SQL queries against your existing database as follows:

conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER);")
conn.execute("INSERT INTO users(id) VALUES (10);")

print(conn.execute("select * from users").fetchall())
5

Sync (Embedded Replicas only)

When using embedded replicas you should call sync() on the connector to sync your local database with the primary database.

conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER);")
conn.execute("INSERT INTO users(id) VALUES (1);")
conn.commit()

conn.sync()

print(conn.execute("select * from users").fetchall())