-
Notifications
You must be signed in to change notification settings - Fork 0
data
Adalfarus edited this page Mar 27, 2024
·
16 revisions
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.
DBManager
serves as an interface for managing SQLite databases.
-
__init__(self, path: str)
: Initializes aDBManager
instance by connecting to the SQLite database specified by thepath
. -
create_table(self, table_name: str, columns: list)
: Creates a table with the specifiedtable_name
andcolumns
if it doesn't already exist. -
update_info(self, info: list, table: str, columns: list)
: Inserts a new row ofinfo
into the specifiedtable
using the specifiedcolumns
. The length ofinfo
must match the number ofcolumns
. -
get_info(self, table: str, columns: list) -> list
: Retrieves data from the specifiedtable
andcolumns
, returning the results as a list of tuples. -
close(self)
: Commits any pending transactions and closes the database connection.
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:
- A
DBManager
instance namedmy_db
is created, connecting to an SQLite database file namedmy_db.db
. - A new table named
my_table
is created with three columns:column1
,column2
, andcolumn3
. - A new row of data is inserted into
my_table
, withinfo1
andinfo3
populatingcolumn1
andcolumn2
, respectively. - Data is retrieved from
my_table
, specifically fromcolumn3
, and printed to the console. - The database connection is closed using the
close
method.
Description