### Install sqlitecloud Package for Testing Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/sqlalchemy-sqlitecloud/README.md Install the sqlitecloud package, either the latest version from PyPI or a local development version. ```bash $ pip install sqlitecloud # last version ``` ```bash $ cd ../src # sqlitecloud src directory $ pip install -e . ``` -------------------------------- ### Install sqlitecloud-py Package Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/README.md Install the sqlitecloud-py library using pip. This is the first step to using the package. ```bash $ pip install sqlitecloud ``` -------------------------------- ### Install sqlalchemy-sqlitecloud Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/sqlalchemy-sqlitecloud/README.md Install the package using pip. This command fetches and installs the latest version from PyPI. ```bash pip install sqlalchemy-sqlitecloud ``` -------------------------------- ### Full SQLAlchemy Example with SQLite Cloud Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/sqlalchemy-sqlitecloud/README.md Demonstrates creating tables, inserting data, and querying data using the SQLAlchemy dialect with a SQLite Cloud database. This example uses declarative models and session management. ```python import sqlalchemy from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.dialects import registry from sqlalchemy.orm import backref, declarative_base, relationship, sessionmaker Base = declarative_base() class Artist(Base): __tablename__ = "artists" ArtistId = Column("ArtistId", Integer, primary_key=True) Name = Column("Name", String) Albums = relationship("Album", backref=backref("artist")) class Album(Base): __tablename__ = "albums" AlbumId = Column("AlbumId", Integer, primary_key=True) ArtistId = Column("ArtistId", Integer, ForeignKey("artists.ArtistId")) Title = Column("Title", String) # SQLite Cloud connection string connection_string = "sqlitecloud://myhost.sqlite.cloud:8860/mydatabase.sqlite?apikey=myapikey" engine = sqlalchemy.create_engine(connection_string) Session = sessionmaker(bind=engine) session = Session() name = "John Doe" query = sqlalchemy.insert(Artist).values(Name=name) result_insert = session.execute(query) title = "The Album" query = sqlalchemy.insert(Album).values( ArtistId=result_insert.lastrowid, Title=title ) session.execute(query) query = ( sqlalchemy.select(Artist, Album) .join(Album, Artist.ArtistId == Album.ArtistId) .where(Artist.ArtistId == result_insert.lastrowid) ) result = session.execute(query).fetchone() print("Artist Name: " + result[0].Name) print("Album Title: " + result[1].Title) ``` -------------------------------- ### Install sqlitecloud Package Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/samples.ipynb Install the necessary sqlitecloud Python package using pip. This is the first step before you can use the library. ```python %pip install sqlitecloud ``` -------------------------------- ### Migrate from sqlite3 to sqlitecloud-py Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/README.md Demonstrates how to switch from using the standard sqlite3 library to sqlitecloud-py by changing the import statement and connection string. This example creates a table, inserts data, and then queries it. ```python # import sqlitecloud import sqlite3 # comment out the following line... conn = sqlite3.connect(":memory:") # ... and uncomment this line and import the sqlitecloud package # (add the database name like in this connection string) # conn = sqlitecloud.connect("sqlitecloud://myhost.sqlite.cloud:8860/mydatabase.sqlite?apikey=myapikey") conn.execute("CREATE TABLE IF NOT EXISTS producers (ProducerId INTEGER PRIMARY KEY, name TEXT, year INTEGER)") conn.executemany( "INSERT INTO producers (name, year) VALUES (?, ?)", [("Sony Music Entertainment", 2020), ("EMI Music Publishing", 2021)], ) cursor = conn.execute("SELECT * FROM producers") for row in cursor: print(row) ``` -------------------------------- ### Insert and Query DataFrame with SQLite Cloud Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/README.md This snippet shows how to read data into a Pandas DataFrame, write it to a SQLite Cloud database, and then query the database to fetch data back into a DataFrame. Ensure you have pandas and sqlitecloud libraries installed. ```python import io import pandas as pd import sqlitecloud dfprices = pd.read_csv( io.StringIO( """DATE,CURRENCY,PRICE 20230504,USD,201.23456 20230503,USD,12.34567 20230502,USD,23.45678 20230501,USD,34.56789""" ) ) conn = sqlitecloud.connect("sqlitecloud://myhost.sqlite.cloud:8860/mydatabase.sqlite?apikey=myapikey") conn.executemany("DROP TABLE IF EXISTS ?", [("PRICES",)]) # Write the dataframe to the SQLite Cloud database as a table PRICES dfprices.to_sql("PRICES", conn, index=False) # Create the dataframe from the table PRICES on the SQLite Cloud database df_actual_prices = pd.read_sql("SELECT * FROM PRICES", conn) # Inspect the dataframe print(df_actual_prices.head()) # Perform a simple query on the dataframe query_result = df_actual_prices.query("PRICE > 50.00") print(query_result) ``` -------------------------------- ### Execute INSERT and SELECT Queries with Parameter Styles Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/samples.ipynb Demonstrates executing INSERT and SELECT queries using both question mark (?) and named (:name) parameter styles for safe query preparation. This helps prevent SQL injection. ```python # You can use the cursor to perform other queries. # Queries can be prepared with `question mark` and `named` style cursor = conn.execute("INSERT INTO genres (Name) values (?)", ("My brand new genre",)) cursor.execute("SELECT * FROM genres WHERE Name like :name", {"name": "My brand%"}) cursor.fetchone() ``` -------------------------------- ### Select Database for Queries Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/samples.ipynb If the database was not specified in the connection string, you can select it using the 'USE DATABASE' SQL command. This ensures subsequent queries target the correct database. ```python # Select the database to use if not specified in the connection string db_name = "chinook.sqlite" conn.execute(f"USE DATABASE {db_name}") ``` -------------------------------- ### Connect to SQLite Cloud and Query Data Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/README.md Connect to a SQLite Cloud instance using a connection string and API key. Demonstrates executing a query and fetching a single result. ```python import sqlitecloud # Open the connection to SQLite Cloud conn = sqlitecloud.connect("sqlitecloud://myhost.sqlite.cloud:8860?apikey=myapikey") # You can autoselect the database during the connect call # by adding the database name as path of the SQLite Cloud # connection string, eg: # conn = sqlitecloud.connect("sqlitecloud://myhost.sqlite.cloud:8860/mydatabase?apikey=myapikey") db_name = "chinook.sqlite" conn.execute(f"USE DATABASE {db_name}") cursor = conn.execute("SELECT * FROM albums WHERE AlbumId = ?", (1, )) result = cursor.fetchone() print(result) conn.close() ``` -------------------------------- ### Run SQLAlchemy SQLite Cloud Test Suite Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/sqlalchemy-sqlitecloud/README.md Execute the test suite for the sqlalchemy-sqlitecloud dialect using pytest. Navigate to the dialect's directory before running the command. ```bash $ cd sqlalchemy-sqlitecloud $ pytest ``` -------------------------------- ### Create SQLAlchemy Engine for SQLite Cloud Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/sqlalchemy-sqlitecloud/README.md Create an SQLAlchemy engine instance using the provided SQLite Cloud connection string. Ensure your connection string is correctly formatted with your node, port, database, and API key. ```python from sqlalchemy import create_engine engine = create_engine('sqlitecloud://mynode.sqlite.io?apikey=key1234') ``` -------------------------------- ### Establish SQLite Cloud Connection Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/samples.ipynb Connect to your SQLite Cloud database using a provided connection string. Ensure your API key and database details are correct. The database name can be included in the connection string. ```python import sqlitecloud # You can autoselect the database during the connection by adding the database name as path of the SQLite Cloud connection string, eg: # conn = sqlitecloud.connect("sqlitecloud://myhost.sqlite.cloud:8860/mydatabase?apikey=myapikey") sqlitecloud_connection_string = "sqlitecloud://myhost.sqlite.cloud:8860/mydatabase?apikey=myapikey" # Open the connection to SQLite Cloud conn = sqlitecloud.connect(sqlitecloud_connection_string) ``` -------------------------------- ### Execute SELECT Query and Fetch One Row Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/samples.ipynb Execute a SELECT query to retrieve data. The result is a Cursor object from which you can fetch rows. fetchone() retrieves a single row. ```python # The execution of the query generate the `Cursor` object # to fetch the results. cursor = conn.execute("SELECT * FROM albums") cursor.fetchone() ``` -------------------------------- ### SQLAlchemy ORM with SQLite Cloud Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/README.md Defines SQLAlchemy ORM models for 'artists' and 'albums' tables and demonstrates inserting and querying data using a SQLite Cloud connection string. Ensure your connection string is correctly formatted with your host, port, database name, and API key. ```python import sqlalchemy from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.dialects import registry from sqlalchemy.orm import backref, declarative_base, relationship, sessionmaker Base = declarative_base() class Artist(Base): __tablename__ = "artists" ArtistId = Column("ArtistId", Integer, primary_key=True) Name = Column("Name", String) Albums = relationship("Album", backref=backref("artist")) class Album(Base): __tablename__ = "albums" AlbumId = Column("AlbumId", Integer, primary_key=True) ArtistId = Column("ArtistId", Integer, ForeignKey("artists.ArtistId")) Title = Column("Title", String) # SQLite Cloud connection string connection_string = "sqlitecloud://myhost.sqlite.cloud:8860/mydatabase.sqlite?apikey=myapikey" engine = sqlalchemy.create_engine(connection_string) Session = sessionmaker(bind=engine) session = Session() name = "John Doe" query = sqlalchemy.insert(Artist).values(Name=name) result_insert = session.execute(query) title = "The Album" query = sqlalchemy.insert(Album).values( ArtistId=result_insert.lastrowid, Title=title ) session.execute(query) query = ( sqlalchemy.select(Artist, Album) .join(Album, Artist.ArtistId == Album.ArtistId) .where(Artist.ArtistId == result_insert.lastrowid) ) result = session.execute(query).fetchone() print("Artist Name: " + result[0].Name) print("Album Title: " + result[1].Title) ``` -------------------------------- ### Using sqlitecloud with sqlite3 API Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/samples.ipynb Adapt your existing sqlite3 code to use sqlitecloud by simply changing the import statement and connection method. This allows seamless migration to SQLite Cloud. ```python import sqlite3 import sqlitecloud # Comment out the following line # conn = sqlite3.connect(":memory:") # and uncomment this one to use the sqlitecloud package # conn = sqlitecloud.connect(sqlitecloud_connection_string) conn.execute( "CREATE TABLE IF NOT EXISTS producers (ProducerId INTEGER PRIMARY KEY, name TEXT, year INTEGER)" ) conn.executemany( "INSERT INTO producers (name, year) VALUES (?, ?)", [("Sony Music Entertainment", 2020), ("EMI Music Publishing", 2021)], ) cursor = conn.execute("SELECT * FROM producers") for row in cursor: print(row) ``` -------------------------------- ### Querying DataFrames with Pandas Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/samples.ipynb Perform data analysis directly on Pandas DataFrames fetched from SQLite Cloud. Use Pandas query methods for filtering and manipulation. ```python # Perform a simple query on the dataframe query_result = df_actual_prices.query("PRICE > 50.00") print(query_result) ``` -------------------------------- ### Pandas DataFrame Integration with SQLite Cloud Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/samples.ipynb Use Pandas DataFrames to easily load data from CSV into SQLite Cloud and query data from SQLite Cloud into DataFrames. This simplifies data manipulation and analysis workflows. ```python import io import pandas as pd import sqlitecloud dfprices = pd.read_csv( io.StringIO( """DATE,CURRENCY,PRICE 20230504,USD,201.23456 20230503,USD,12.34567 20230502,USD,23.45678 20230501,USD,34.56789""" ) ) conn = sqlitecloud.connect(sqlitecloud_connection_string) conn.executemany("DROP TABLE IF EXISTS ?", [("PRICES",)]) # Write the dataframe to the SQLite Cloud database as a table PRICES dfprices.to_sql("PRICES", conn, index=False) # Create the dataframe from the table PRICES on the SQLite Cloud database df_actual_prices = pd.read_sql("SELECT * FROM PRICES", conn) # Inspect the dataframe print(df_actual_prices.head()) ``` -------------------------------- ### Close SQLite Cloud Connection Source: https://github.com/sqlitecloud/sqlitecloud-py/blob/main/samples.ipynb It is important to close the database connection when you are finished to free up resources. Use the close() method on the connection object. ```python # When you are done clean up the connection conn.close() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.