Skip to content
Adalfarus edited this page Mar 27, 2024 · 16 revisions

database

The database module provides a simplified interface for interacting with databases. It encapsulates database connections, table creation, data insertion, and data retrieval into a convenient object-oriented interface.

Classes

DBManager

DBManager serves as an interface for managing SQLite databases.

Methods

  • __init__(self, path: str): Initializes a DBManager instance by connecting to the SQLite database specified by the path.
  • create_table(self, table_name: str, columns: list): Creates a table with the specified table_name and columns if it doesn't already exist.
  • update_info(self, info: list, table: str, columns: list): Inserts a new row of info into the specified table using the specified columns. The length of info must match the number of columns.
  • get_info(self, table: str, columns: list) -> list: Retrieves data from the specified table and columns, returning the results as a list of tuples.
  • close(self): Commits any pending transactions and closes the database connection.

Usage

The following example demonstrates how to use the DBManager class to interact with an SQLite database:

from aplustools.database import DBManager

# Create a new DBManager instance, connecting to my_db.db
my_db = DBManager("./my_db.db")

# Create a new table named my_table with three columns
my_db.create_table("my_table", ["column1", "column2", "column3"])

# Insert a new row of data into my_table
my_db.update_info(["info1", "info3"], "my_table", ["column1", "column2"])

# Retrieve and print data from my_table
print(my_db.get_info("my_table", ["column3"]))

# Close the database connection
my_db.close()

In this example:

  1. A DBManager instance named my_db is created, connecting to an SQLite database file named my_db.db.
  2. A new table named my_table is created with three columns: column1, column2, and column3.
  3. A new row of data is inserted into my_table, with info1 and info3 populating column1 and column2, respectively.
  4. Data is retrieved from my_table, specifically from column3, and printed to the console.
  5. The database connection is closed using the close method.

faker

Description

Clone this wiki locally