sqlite3 Python(開発者向けのしくみ)
Pythonのsqlite3モジュールは、SQLiteデータベースと対話する方法を提供します。 これはPython標準ライブラリの一部であるため、それを使用するために何か追加でインストールする必要はありません。 その機能を探求し、一部のコード例を見てみましょう。 この記事の後半では、Iron Softwareによって開発されたPDF生成ライブラリであるIronPDFを探求します。
SQLiteは、別個のデータベースサーバープロセスを必要としない、軽量でディスクベースのデータベースです。 sqlite3モジュールは、既存のデータベースまたは新しく作成されたデータベースとシームレスにやり取りするためのSQLインターフェース準拠の環境を提供します。 このモジュールは、PEP 249で記述されたDB-API 2.0仕様を強制します。
基本的な使用法
ここでは、sqlite3を始めるための簡単な例と複数のSQLステートメントを示します。
データベースへの接続
まず、SQLiteデータベースに接続する必要があります。 もしデータベースファイルがない場合は、生成されます:
import sqlite3
# Connect to the database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create a cursor object
cur = conn.cursor()import sqlite3
# Connect to the database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create a cursor object
cur = conn.cursor()テーブルを作成する
新しいデータテーブルを作成するためにCREATE TABLE SQLステートメントを使用します:
# Create a table using SQL statements
cur.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')# Create a table using SQL statements
cur.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')データの挿入
データベーステーブルにデータを挿入する方法はこちらです:
# Insert data into the table
cur.execute('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('Alice', 30))
# Commit the transaction using the connection object
conn.commit()# Insert data into the table
cur.execute('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('Alice', 30))
# Commit the transaction using the connection object
conn.commit()データのクエリ
SQLコマンドを実行し、データベーステーブルから結果を取得します:
# Query the database
cur.execute('SELECT * FROM users')
# Fetch all results
rows = cur.fetchall()
# Print the results
for row in rows:
print(row)# Query the database
cur.execute('SELECT * FROM users')
# Fetch all results
rows = cur.fetchall()
# Print the results
for row in rows:
print(row)データの更新
テーブル内の既存のデータを更新するには:
# Update data in the table
cur.execute('''
UPDATE users SET age = ? WHERE name = ?
''', (31, 'Alice'))
# Commit the transaction
conn.commit()# Update data in the table
cur.execute('''
UPDATE users SET age = ? WHERE name = ?
''', (31, 'Alice'))
# Commit the transaction
conn.commit()データの削除
名前がAliceのデータベースの行からデータを削除するには:
# Delete data from the table
cur.execute('''
DELETE FROM users WHERE name = ?
''', ('Alice',))
# Commit the transaction
conn.commit()# Delete data from the table
cur.execute('''
DELETE FROM users WHERE name = ?
''', ('Alice',))
# Commit the transaction
conn.commit()接続の閉じ方
終了したらカーソルと接続の両方を閉じることを忘れないでください:
# Close the cursor and connection
cur.close()
conn.close()# Close the cursor and connection
cur.close()
conn.close()高度な機能
コンテキストマネージャーの使用
コンテキストマネージャーを使用して接続を自動的に閉じることができます:
with sqlite3.connect('example.db') as conn:
cur = conn.cursor()
cur.execute('SELECT * FROM users')
rows = cur.fetchall()
for row in rows:
print(row)with sqlite3.connect('example.db') as conn:
cur = conn.cursor()
cur.execute('SELECT * FROM users')
rows = cur.fetchall()
for row in rows:
print(row)トランザクションの処理
SQLiteはトランザクションをサポートしており、これらを管理するためにBEGIN, COMMIT, ROLLBACKを使用できます:
try:
conn.execute('BEGIN')
cur.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Bob', 25))
conn.commit()
except sqlite3.Error as e:
conn.rollback()
print(f"An error occurred: {e}")try:
conn.execute('BEGIN')
cur.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Bob', 25))
conn.commit()
except sqlite3.Error as e:
conn.rollback()
print(f"An error occurred: {e}")IronPDFの紹介

IronPDFは、HTML、CSS、画像、JavaScriptを使用してPDFを作成、編集、署名するために設計された強力なPythonライブラリです。 低メモリフットプリントながら商用グレードのパフォーマンスを備えています。 主な機能は以下のとおりです:
HTMLからPDFへの変換:
HTMLファイル、HTML文字列、およびURLをPDFに変換します。 たとえば、Chrome PDFレンダラーを使用してウェブページをPDFとしてレンダリングします。
クロスプラットフォームサポート:
.NET Core、.NET Standard、.NET Frameworkを含むさまざまな.NETプラットフォームと互換性があります。 Windows、Linux、macOSをサポートしています。
編集と署名:
プロパティを設定し、パスワードと権限でセキュリティを追加し、PDFにデジタル署名を適用します。
ページテンプレートと設定:
ヘッダー、フッター、ページ番号、調整可能な余白を使用してPDFをカスタマイズします。 レスポンシブレイアウトとカスタム用紙サイズをサポートしています。
標準準拠:
PDF/AやPDF/UAなどのPDF標準に準拠しており、UTF-8文字エンコーディングをサポートし、画像、CSS、フォントなどのアセットを管理します。
IronPDFとSQLite3 Pythonを使用してPDFドキュメントを生成する
import sqlite3
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
# Connect to the sqlite database file (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create a cursor object for database connection
cur = conn.cursor()
# Create a table SQL command
cur.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')
# Insert data into the table
cur.execute('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser1', 30))
cur.execute('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser2', 31))
cur.execute('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser3', 25))
cur.execute('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser4', 28))
# Commit the transaction using the connection object
conn.commit()
# Query the database
cur.execute('SELECT * FROM users')
# Fetch all results
rows = cur.fetchall()
# Print the results
for row in rows:
print(row)
# Update data in the table
cur.execute('''
UPDATE users SET age = ? WHERE name = ?
''', (31, 'Alice'))
# Commit the transaction
conn.commit()
# Delete data from the table
cur.execute('''
DELETE FROM users WHERE name = ?
''', ('IronUser1',))
# Commit the transaction
conn.commit()
# Initialize PDF renderer
renderer = ChromePdfRenderer()
# Create a PDF from an HTML string using Python
content = "<h1>Awesome Iron PDF with Sqlite3</h1>"
content += "<p>table data</p>"
for row in rows:
content += "<p>" + str(row) + "</p>"
# Close the cursor and connection
cur.close()
conn.close()
# Render the HTML as a PDF
pdf = renderer.RenderHtmlAsPdf(content)
# Export to a file
pdf.SaveAs("DemoSqlite3.pdf")import sqlite3
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
# Connect to the sqlite database file (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create a cursor object for database connection
cur = conn.cursor()
# Create a table SQL command
cur.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
)
''')
# Insert data into the table
cur.execute('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser1', 30))
cur.execute('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser2', 31))
cur.execute('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser3', 25))
cur.execute('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('IronUser4', 28))
# Commit the transaction using the connection object
conn.commit()
# Query the database
cur.execute('SELECT * FROM users')
# Fetch all results
rows = cur.fetchall()
# Print the results
for row in rows:
print(row)
# Update data in the table
cur.execute('''
UPDATE users SET age = ? WHERE name = ?
''', (31, 'Alice'))
# Commit the transaction
conn.commit()
# Delete data from the table
cur.execute('''
DELETE FROM users WHERE name = ?
''', ('IronUser1',))
# Commit the transaction
conn.commit()
# Initialize PDF renderer
renderer = ChromePdfRenderer()
# Create a PDF from an HTML string using Python
content = "<h1>Awesome Iron PDF with Sqlite3</h1>"
content += "<p>table data</p>"
for row in rows:
content += "<p>" + str(row) + "</p>"
# Close the cursor and connection
cur.close()
conn.close()
# Render the HTML as a PDF
pdf = renderer.RenderHtmlAsPdf(content)
# Export to a file
pdf.SaveAs("DemoSqlite3.pdf")コードの説明
このPythonプログラムは、SQLiteライブラリを使用してデータベースを作成し、データを挿入し、クエリを実行し、レコードを更新し、削除し、最後にIronPDFを使用してPDFドキュメントを生成する方法を示します。
ライブラリのインポート:
sqlite3: SQLiteデータベースを操作するためのPythonの組み込みモジュール。ironpdf: PDFの生成を可能にするIronPDFからコンポーネントをインポートします。
データベースへの接続:
example.dbという名前のSQLiteデータベースへの接続を確立します。
テーブルの作成:
- 列
id(INTEGER, PRIMARY KEY)、name(TEXT, NOT NULL)、age(INTEGER)を持つusersというSQLiteテーブルを定義します。
- 列
データの挿入:
usersテーブルに複数のデータ行を挿入します。
トランザクションのコミット:
- データベースへの変更を永続的にするためにコミットします。
データベースのクエリ:
usersテーブルからすべての行を取得するSELECTステートメントを実行します。
データの更新:
- 'Alice'という名のユーザーの
ageを更新します。
- 'Alice'という名のユーザーの
データの削除:
- 'IronUser1'という名のユーザーを
usersテーブルから削除します。
- 'IronUser1'という名のユーザーを
PDFの生成:
- IronPDF (
ChromePdfRenderer)を使用してHTMLコンテンツからPDFドキュメントを作成します。 - ヘッダーとテーブルデータ(データベースから取得したもの)をHTMLコンテンツに結合します。
- PDFドキュメントを
DemoSqlite3.pdfとして保存します。
- IronPDF (
- 接続の終了:
- リソースを解放するためにカーソル(
cur)と接続(conn)を閉じます。
- リソースを解放するためにカーソル(
このスクリプトは、PythonのSQLite3とIronPDFライブラリを使用したデータベースのセットアップからデータ操作とPDF生成までの完全なワークフローを示しています。
出力


IronPDFライセンス
IronPDFはライセンスキーで動作します。 IronPDF for Pythonは、購入前にその広範な機能をテストできる無料の試用ライセンスキーを提供しています。
ライセンスキーをここに配置します:
import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";結論

sqlite3モジュールは、PythonでSQLiteデータベースを操作するための強力で使いやすいツールです。 Python標準ライブラリへの統合により、単純なデータベース操作から複雑な操作までを便利に行うことができます。 IronPDFは試用ライセンスを提供します。 その後、ライセンスは$799から開始し、さらに上昇します。










