Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is a possible procedure for creating a method to retrieve a SQLite SQLITE_ROW entry based on the column name and datatype:

  1. Define the inputs and outputs of the method. The method should take the following inputs:

    • a SQLite statement object containing the query result
    • the name of the column to retrieve the entry from
    • the expected datatype of the entry. The method should return the entry as a value of the expected datatype, or None if the entry is not found or is not of the expected datatype.
  2. Parse the query result to retrieve the index of the column with the specified name. SQLite statement objects have a method called "column_index" that can be used for this purpose. If the column does not exist in the result, return None.

  3. Parse the row at the current position in the query result to retrieve the value of the column at the specified index. SQLite statement objects have a method called "column_value" that can be used for this purpose. If the column value is NULL, return None.

  4. Check the datatype of the column value against the expected datatype. If they do not match, return None.

  5. If the datatype matches, return the column value as a value of the expected datatype.

Here is an example implementation of this procedure in Python:

def get_column_entry(stmt, col_name, expected_type):
    col_idx = stmt.column_index(col_name)
    if col_idx < 0:
        return None
    col_value = stmt.column_value(col_idx)
    if col_value is None:
        return None
    if type(col_value) != expected_type:
        return None
    return col_value

This method can be used like this:

stmt = conn.execute("SELECT * FROM my_table WHERE id = ?", [123])
row = stmt.fetchone()
id_value = get_column_entry(stmt, "id", int)
name_value = get_column_entry(stmt, "name", str)

This would retrieve the row with ID 123 from the "my_table" table, and then retrieve the values of the "id" and "name" columns from the row, making sure that they are integers and strings, respectively. If any of the values are missing or have the wrong datatype, the corresponding variables would be set to None.