푸터 콘텐츠로 바로가기
PYTHON 도움말

sqlite 유틸리티 Python(개발자를 위한 작동 방식)

The SQLite-utils Python package is a versatile tool that contains Python utility functions for working with SQLite databases. It provides a command-line interface (CLI) and a Python library, making it easy to create, manipulate, and query SQLite databases. Let's dive into its features and see some code examples. Later in this article, we will explore IronPDF, a PDF generation library developed by Iron Software.

Overview of SQLite-utils

SQLite-utils is designed to simplify various tasks related to manipulating SQLite databases. Some of its key features include:

  • Creating and managing databases: Easily create new databases and tables.
  • Inserting and querying data: Insert JSON data, CSV, or TSV files and run SQL queries.
  • Full-text search: Configure and run full-text search queries.
  • Schema transformations: Perform schema changes that SQLite's ALTER TABLE does not support directly.
  • Data normalization: Extract columns into separate tables to normalize data.
  • Custom SQL functions: Install plugins to add custom SQL functions.

Installation

You can install SQLite-utils using pip:

pip install sqlite-utils
pip install sqlite-utils
SHELL

Or, if you use Homebrew on macOS:

brew install sqlite-utils
brew install sqlite-utils
SHELL

Using SQLite-utils as a CLI Tool

The CLI tool allows you to perform various operations directly from the command line. Here are some examples:

Creating a Database and Inserting Data

Let's create a new SQLite database and insert some data from a CSV file:

# Create a new database and insert data from a CSV file
sqlite-utils insert dogs.db dogs dogs.csv --csv
# Create a new database and insert data from a CSV file
sqlite-utils insert dogs.db dogs dogs.csv --csv
SHELL

Querying Data

The command below is how you would perform an SQL query from the database:

# Query the database and display results in JSON format
sqlite-utils dogs.db "select * from dogs" --json
# Query the database and display results in JSON format
sqlite-utils dogs.db "select * from dogs" --json
SHELL

Listing Tables

List all tables in the database along with their row counts:

sqlite-utils tables dogs.db --counts
sqlite-utils tables dogs.db --counts
SHELL

Using SQLite-utils as a Python Library

You can also use SQLite-utils as a Python library to interact with SQLite databases programmatically.

Creating a Database and Inserting Data

Here's how to create a new database and insert data using Python:

import sqlite_utils

# Create a new database
db = sqlite_utils.Database("demo_database.db")

# Insert data into a table
db["dogs"].insert_all([
    {"id": 1, "age": 4, "name": "Cleo"},
    {"id": 2, "age": 2, "name": "Pancakes"}
], pk="id")
import sqlite_utils

# Create a new database
db = sqlite_utils.Database("demo_database.db")

# Insert data into a table
db["dogs"].insert_all([
    {"id": 1, "age": 4, "name": "Cleo"},
    {"id": 2, "age": 2, "name": "Pancakes"}
], pk="id")
PYTHON

Querying Data

You can run SQL queries and fetch results:

# Run a query and fetch results
rows = db.query("SELECT * FROM dogs")
for row in rows:
    print(row)
# Run a query and fetch results
rows = db.query("SELECT * FROM dogs")
for row in rows:
    print(row)
PYTHON

Enable full-text search on a table and execute search queries:

# Enable full-text search on the 'name' column
db["dogs"].enable_fts(["name"])

# Run a search query for the term "Cleo"
results = db["dogs"].search("Cleo")
for result in results:
    print(result)
# Enable full-text search on the 'name' column
db["dogs"].enable_fts(["name"])

# Run a search query for the term "Cleo"
results = db["dogs"].search("Cleo")
for result in results:
    print(result)
PYTHON

Introducing IronPDF

sqlite utils Python (How It Works For Developers): Figure 1 - IronPDF: The Python PDF Library

IronPDF is a powerful Python library designed to create, edit, and sign PDFs using HTML, CSS, images, and JavaScript. It offers commercial-grade performance with a low memory footprint. Key features include:

HTML to PDF Conversion:

Convert HTML files, HTML strings, and URLs to PDFs. For example, render a webpage as a PDF using the Chrome PDF renderer.

Cross-Platform Support:

Compatible with various .NET platforms, including .NET Core, .NET Standard, and .NET Framework. It supports Windows, Linux, and macOS.

Editing and Signing:

Set properties, add security with passwords and permissions, and apply digital signatures to your PDFs.

Page Templates and Settings:

You can customize PDFs with headers, footers, page numbers, and adjustable margins. It additionally supports custom paper sizes and responsive layouts.

Standards Compliance:

Complies with PDF standards, including PDF/A and PDF/UA, supports UTF-8 character encoding, and manages assets such as images, CSS, and fonts.

Generate PDF Documents using IronPDF and Sqlite Utils

import sqlite_utils
from ironpdf import ChromePdfRenderer, License

# Apply your license key
License.LicenseKey = "key"

# Initialize a new database
db = sqlite_utils.Database("mydatabase.db")

# Define a table schema
schema = {
    "id": int,
    "name": str,
    "age": int
}

# Create a table with the defined schema
db["users"].create(schema)

# Sample data to insert into the table
data = [
    {"id": 1, "name": "Alice", "age": 30},
    {"id": 2, "name": "Bob", "age": 28},
    {"id": 3, "name": "Charlie", "age": 32}
]

# Insert data into the table
db["users"].insert_all(data)

# Query all records from the table
rows = db.query("SELECT * FROM users")

# Initialize the PDF renderer
renderer = ChromePdfRenderer()

# Create HTML content for the PDF
content = "<h1>Awesome IronPDF with Sqlite-Utils</h1>"
content += "<p>Table data:</p>"
for row in rows:
    content += f"<p>{row}</p>"

# Render the HTML content as PDF
pdf = renderer.RenderHtmlAsPdf(content)

# Save the generated PDF as a file
pdf.save_as("DemoSqliteUtils.pdf")
import sqlite_utils
from ironpdf import ChromePdfRenderer, License

# Apply your license key
License.LicenseKey = "key"

# Initialize a new database
db = sqlite_utils.Database("mydatabase.db")

# Define a table schema
schema = {
    "id": int,
    "name": str,
    "age": int
}

# Create a table with the defined schema
db["users"].create(schema)

# Sample data to insert into the table
data = [
    {"id": 1, "name": "Alice", "age": 30},
    {"id": 2, "name": "Bob", "age": 28},
    {"id": 3, "name": "Charlie", "age": 32}
]

# Insert data into the table
db["users"].insert_all(data)

# Query all records from the table
rows = db.query("SELECT * FROM users")

# Initialize the PDF renderer
renderer = ChromePdfRenderer()

# Create HTML content for the PDF
content = "<h1>Awesome IronPDF with Sqlite-Utils</h1>"
content += "<p>Table data:</p>"
for row in rows:
    content += f"<p>{row}</p>"

# Render the HTML content as PDF
pdf = renderer.RenderHtmlAsPdf(content)

# Save the generated PDF as a file
pdf.save_as("DemoSqliteUtils.pdf")
PYTHON

Code Explanation

This script combines the functionalities of the SQLite-utils Python package and IronPDF library to manage an SQLite database and generate a PDF document. The following is a step-by-step explanation of what the code does:

  1. Database Initialization:

    • Initializes an SQLite database named "mydatabase.db" using SQLite-utils.
  2. Table Creation:

    • Defines a table schema with columns id, name, and age.
    • Creates a table named "users" in the SQLite database using the defined schema.
  3. Data Insertion:

    • Inserts multiple records into the "users" table using SQLite-utils.
  4. Data Querying:

    • Retrieves all records from the "users" table and creates an HTML representation of the data.
  5. PDF Generation:
    • Utilizes IronPDF to create a PDF document.
    • Constructs HTML content for the PDF document, including headers and table data retrieved from the SQLite database.
    • Saves the generated PDF document as "DemoSqliteUtils.pdf."

Overall, this script demonstrates how to leverage SQLite-utils for database management tasks such as table creation, data insertion, and querying, combined with IronPDF for generating PDF documents from dynamic content sourced from an SQLite database in Python applications.

Output

sqlite utils Python (How It Works For Developers): Figure 2 - Example console output

PDF

sqlite utils Python (How It Works For Developers): Figure 3 - Example PDF output utilizing IronPDF to generate a report

IronPDF License

IronPDF runs on the Python license key. IronPDF for Python offers a free trial license key to allow users to test its extensive features before purchasing.

Place the License Key at the start of the script before using IronPDF package:

from ironpdf import License

# Apply your license key
License.LicenseKey = "key"
from ironpdf import License

# Apply your license key
License.LicenseKey = "key"
PYTHON

Conclusion

SQLite-utils is a powerful tool for working with SQLite databases. It offers both a CLI and a Python library. Whether you need to quickly manipulate data from the command line or integrate SQLite operations into your Python applications, SQLite provides a flexible and easy-to-use solution.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.