This is currently in technical preview. Join us in Discord to report any issues.

In this C quickstart we will learn how to:

  • Retrieve database credentials
  • Install the libSQL package
  • Connect to a local or remote 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 make sure to handle database tokens securely.

2

Install

To use libSQL with C, you need to build the library from source:

libSQL C

Build from source code

After building, make sure to link against the library when compiling your C program:

gcc -o your_program your_program.c -L/path/to/libsql/lib -llibsql
3

Connect

You must first initialize libSQL, create a libsql_database_t object, and then open a libsql_connection_t to it:

4

Execute

You can execute a SQL query against your existing database by preparing a statement and then executing it:

libsql_statement_t stmt = libsql_connection_prepare(conn, "SELECT * FROM users");
libsql_rows_t rows = libsql_statement_query(stmt);

If you need to use placeholders for values, you can do that:

5

Sync (Embedded Replicas only)

When using embedded replicas, you should call libsql_database_sync() on the database to sync your local database with the primary database, unless you are using sync_interval (though there is no issue with calling sync with sync_interval enabled):

libsql_sync_t sync = libsql_database_sync(db);
if (sync.err) {
    fprintf(stderr, "Error syncing database: %s\n", libsql_error_message(sync.err));
} else {
    printf("Sync completed. Frame number: %llu, Frames synced: %llu\n",
            (unsigned long long)sync.frame_no,
            (unsigned long long)sync.frames_synced);
}