5.2. SimpleSQLite class

class simplesqlite.SimpleSQLite(database_path, mode='a', is_create_table_config=True, profile=False)[source]

Bases: object

Wrapper class of sqlite3 module.

Parameters:
  • database_path (str) – File path of the database to be connected.
  • mode (str) – Open mode.
  • profile (bool) – Recording SQL query execution time profile, if the value is True.
check_connection()[source]
Raises:

simplesqlite.NullDatabaseConnectionError – If not connected to a SQLite database file.

Examples:
from simplesqlite import SimpleSQLite, NullDatabaseConnectionError
import six

con = SimpleSQLite("sample.sqlite", "w")
six.print_("---- connected to a database ----")
con.check_connection()
six.print_("---- disconnected from a database ----")
con.close()
try:
    con.check_connection()
except NullDatabaseConnectionError as e:
    six.print_(e)
---- connected to a database ----
---- disconnected from a database ----
null database connection
close()[source]

Commit and close the connection.

commit()[source]
connect(database_path, mode='a')[source]
Parameters:
  • database_path (str) – Path to the SQLite database file to be connected.
  • mode (str) – "r": Open for read only. "w": Open for read/write. Delete existing tables when connecting. "a": Open for read/write. Append to the existing tables.
Raises:
  • ValueError – If database_path is invalid or mode is invalid.
  • sqlite3.OperationalError – If unable to open the database file.
connection
Returns:sqlite3.Connection instance of the connected database.
Return type:sqlite3.Connection
create_index(table_name, attribute_name)[source]
Parameters:
  • table_name (str) – Table name that contains the attribute to be indexed.
  • attribute_name (str) – Attribute name to create index.
Raises:
create_index_list(table_name, attribute_name_list)[source]
Parameters:
  • table_name (str) – Table name that exists attribute.
  • attribute_name_list (list) – List of attribute names to create indices.

See also

create_index()

create_table(table_name, attribute_description_list)[source]
Parameters:
  • table_name (str) – Table name to create.
  • attribute_description_list (list) – List of table description.
Raises:
create_table_from_csv(csv_source, table_name='', attribute_name_list=(), delimiter=', ', quotechar='"', encoding='utf-8')[source]

Create a table from a CSV file/text.

Parameters:
  • csv_source (str) – Path to the CSV file or CSV text.
  • table_name (str) – Table name to create. Use csv file basename as the table name if the value is empty.
  • attribute_name_list (list) – Attribute names of the table. Use the first line of the csv file as attribute list if attribute_name_list is empty.
  • delimiter (str) – A one-character string used to separate fields.
  • quotechar (str) – A one-character string used to quote fields containing special characters, such as the delimiter or quotechar, or which contain new-line characters.
  • encoding (str) – csv file encoding.
Raises:

ValueError – If the csv data is invalid.

create_table_from_json(json_source, table_name='')[source]

Create a table from a JSON file/text.

Parameters:
  • json_source (str) – Path to the JSON file or JSON text.
  • table_name (str) – Table name to create.
create_table_from_tabledata(tabledata)[source]

Create a table from loader.data.TableData.

Parameters:tabledata (TableData) – Table data to create.
create_table_with_data(table_name, attribute_name_list, data_matrix, index_attribute_list=())[source]

Create a table if not exists. And insert data into the created table.

Parameters:
  • table_name (str) – Table name to create.
  • attribute_name_list (list) – List of attribute names of the table.
  • data_matrix (List of dict/namedtuple()/list/tuple) – Data to be inserted into the table.
  • index_attribute_list (tuple) – List of attribute names of create indices.
Raises:

ValueError – If the data_matrix is empty.

database_path
Returns:

File path of the connected database.

Return type:

str

Examples:
>>> from simplesqlite import SimpleSQLite
>>> con = SimpleSQLite("sample.sqlite", "w")
>>> con.database_path
'/tmp/sample.sqlite'
>>> con.close()
>>> print(con.database_path)
None
drop_table(table_name)[source]
Parameters:

table_name (str) – Table name to drop.

Raises:
execute_query(query, caller=None)[source]

Execute arbitrary SQLite query.

Parameters:
Returns:

Result of the query execution.

Return type:

sqlite3.Cursor

Raises:

Warning

This method can execute an arbitrary query. i.e. No access permissions check by mode.

get_attribute_name_list(table_name)[source]
Returns:

List of attribute names in the table.

Return type:

list

Raises:
Examples:
from simplesqlite import SimpleSQLite, TableNotFoundError
import six

table_name = "sample_table"
con = SimpleSQLite("sample.sqlite", "w")
con.create_table_with_data(
    table_name=table_name,
    attribute_name_list=["attr_a", "attr_b"],
    data_matrix=[[1, "a"], [2, "b"]])

six.print_(con.get_attribute_name_list(table_name))
try:
    six.print_(con.get_attribute_name_list("not_existing"))
except TableNotFoundError as e:
    six.print_(e)
['attr_a', 'attr_b']
'not_existing' table not found in /tmp/sample.sqlite
get_attribute_type_list(table_name)[source]
Returns:

List of attribute names in the table.

Return type:

list

Raises:
get_profile(profile_count=50)[source]

Get profile of query execution time.

Parameters:

profile_count (int) – Number of profiles to retrieve, counted from the top query in descending order by the cumulative execution time.

Returns:

Profile information for each query.

Return type:

list of namedtuple()

Raises:
get_sqlite_master()[source]

Get sqlite_master table information as a list of dictionaries.

Returns:

sqlite_master table information.

Return type:

list

Raises:

simplesqlite.NullDatabaseConnectionError – If not connected to a SQLite database file.

Examples:
import json
from simplesqlite import SimpleSQLite

con = SimpleSQLite("sample.sqlite", "w")
data_matrix = [
    [1, 1.1, "aaa", 1,   1],
    [2, 2.2, "bbb", 2.2, 2.2],
    [3, 3.3, "ccc", 3,   "ccc"],
]
con.create_table_with_data(
    table_name="sample_table",
    attribute_name_list=["a", "b", "c", "d", "e"],
    data_matrix=data_matrix,
    index_attribute_list=["a"])
print(json.dumps(con.get_sqlite_master(), indent=4))
[
    {
        "tbl_name": "sample_table",
        "sql": "CREATE TABLE 'sample_table' ('a' INTEGER, 'b' REAL, 'c' TEXT, 'd' REAL, 'e' TEXT)",
        "type": "table",
        "name": "sample_table",
        "rootpage": 2
    },
    {
        "tbl_name": "sample_table",
        "sql": "CREATE INDEX sample_table_a_index ON sample_table('a')",
        "type": "index",
        "name": "sample_table_a_index",
        "rootpage": 3
    }
]
get_table_name_list()[source]
Returns:

List of table names in the database.

Return type:

list

Raises:
Examples:
from simplesqlite import SimpleSQLite
import six

table_name = "sample_table"
con = SimpleSQLite("sample.sqlite", "w")
con.create_table_with_data(
    table_name="hoge",
    attribute_name_list=["attr_a", "attr_b"],
    data_matrix=[[1, "a"], [2, "b"]])
six.print_(con.get_table_name_list())
[u'hoge']
get_total_changes()[source]
get_value(select, table_name, where=None, extra=None)[source]

Get a value from the table.

Parameters:
  • select (str) – Attribute for SELECT query
  • table_name (str) – Table name of executing the query.
Returns:

Result of execution of the query.

Raises:
has_attribute(table_name, attribute_name)[source]
Parameters:
  • table_name (str) – Table name that exists attribute.
  • attribute_name (str) – Attribute name to be tested.
Returns:

True if the table has the attribute.

Return type:

bool

Raises:

simplesqlite.TableNotFoundError – If the table not found in the database.

Examples:
from simplesqlite import SimpleSQLite, TableNotFoundError
import six

table_name = "sample_table"
con = SimpleSQLite("sample.sqlite", "w")
con.create_table_with_data(
    table_name=table_name,
    attribute_name_list=["attr_a", "attr_b"],
    data_matrix=[[1, "a"], [2, "b"]])

six.print_(con.has_attribute(table_name, "attr_a"))
six.print_(con.has_attribute(table_name, "not_existing"))
try:
    six.print_(con.has_attribute("not_existing", "attr_a"))
except TableNotFoundError as e:
    six.print_(e)
True
False
'not_existing' table not found in /tmp/sample.sqlite
has_attribute_list(table_name, attribute_name_list)[source]
Parameters:
  • table_name (str) – Table name that exists attribute.
  • attribute_name_list (str) – Attribute names to be tested.
Returns:

True if the table has all of the attribute.

Return type:

bool

Raises:

simplesqlite.TableNotFoundError – If the table not found in the database.

Examples:
from simplesqlite import SimpleSQLite, TableNotFoundError
import six

table_name = "sample_table"
con = SimpleSQLite("sample.sqlite", "w")
con.create_table_with_data(
    table_name=table_name,
    attribute_name_list=["attr_a", "attr_b"],
    data_matrix=[[1, "a"], [2, "b"]])

six.print_(con.has_attribute_list(table_name, ["attr_a"]))
six.print_(con.has_attribute_list(
    table_name, ["attr_a", "attr_b"]))
six.print_(con.has_attribute_list(
    table_name, ["attr_a", "attr_b", "not_existing"]))
try:
    six.print_(con.has_attribute("not_existing", ["attr_a"]))
except TableNotFoundError as e:
    six.print_(e)
True
True
False
'not_existing' table not found in /tmp/sample.sqlite
has_table(table_name)[source]
Parameters:

table_name (str) – Table name to be tested.

Returns:

True if the database has the table.

Return type:

bool

Examples:
from simplesqlite import SimpleSQLite
import six

con = SimpleSQLite("sample.sqlite", "w")
con.create_table_with_data(
    table_name="hoge",
    attribute_name_list=["attr_a", "attr_b"],
    data_matrix=[[1, "a"], [2, "b"]])
six.print_(con.has_table("hoge"))
six.print_(con.has_table("not_existing"))
True
False
insert(table_name, insert_record)[source]

Execute INSERT query.

Parameters:
Raises:
insert_many(table_name, insert_record_list)[source]

Execute INSERT query for multiple records.

Parameters:
Raises:
is_connected()[source]
Returns:

True if the connection to a database is valid.

Return type:

bool

Examples:
>>> from simplesqlite import SimpleSQLite
>>> con = SimpleSQLite("sample.sqlite", "w")
>>> con.is_connected()
True
>>> con.close()
>>> con.is_connected()
False
mode
Returns:Connection mode: "r"/"w"/"a".
Return type:str

See also

connect()

rollback()[source]
select(select, table_name, where=None, extra=None)[source]

Execute SELECT query.

Parameters:
  • select (str) – Attribute for the SELECT query.
  • table_name (str) – Table name of executing the query.
Returns:

Result of the query execution.

Return type:

sqlite3.Cursor

Raises:
update(table_name, set_query, where=None)[source]

Execute UPDATE query.

Parameters:
  • table_name (str) – Table name of executing the query.
  • set_query (str) –
Raises:
validate_access_permission(valid_permission_list)[source]
Parameters:

valid_permission_list (list/tuple) – List of permissions that access is allowed.

Raises:
verify_attribute_existence(table_name, attribute_name)[source]
Parameters:
  • table_name (str) – Table name that exists attribute.
  • attribute_name (str) – Attribute name to be tested.
Raises:
Examples:
from simplesqlite import SimpleSQLite, TableNotFoundError, AttributeNotFoundError
import six

table_name = "sample_table"
con = SimpleSQLite("sample.sqlite", "w")
con.create_table_with_data(
    table_name=table_name,
    attribute_name_list=["attr_a", "attr_b"],
    data_matrix=[[1, "a"], [2, "b"]])

con.verify_attribute_existence(table_name, "attr_a")
try:
    con.verify_attribute_existence(table_name, "not_existing")
except AttributeNotFoundError as e:
    six.print_(e)
try:
    con.verify_attribute_existence("not_existing", "attr_a")
except TableNotFoundError as e:
    six.print_(e)
'not_existing' attribute not found in 'sample_table' table
'not_existing' table not found in /tmp/sample.sqlite
verify_table_existence(table_name)[source]
Parameters:

table_name (str) – Table name to be tested.

Raises:
Examples:
from simplesqlite import SimpleSQLite, TableNotFoundError
import six

table_name = "sample_table"
con = SimpleSQLite("sample.sqlite", "w")
con.create_table_with_data(
    table_name=table_name,
    attribute_name_list=["attr_a", "attr_b"],
    data_matrix=[[1, "a"], [2, "b"]])

con.verify_table_existence(table_name)
try:
    con.verify_table_existence("not_existing")
except TableNotFoundError as e:
    six.print_(e)
'not_existing' table not found in /tmp/sample.sqlite