A query in SQLite3 with python
<p>I'm testing a query with python and sqlite3. First method works fine, but 
second is not working. It is about the defined type of variable containing the resgisters in <code>DB</code>:</p>



<pre><code>import sqlite3

def insertar():

    db1=sqlite3.connect('tabla.db')
    print("Estas en la funcion insertar")

    nombre1=raw_input("Escribe el titulo de la novela: ")
    autor1=raw_input("Escribe el autor de la novela: ")
    year1=str(input("Digita el any de la novela: "))

    consulta=db1.cursor()

    strConsulta = "insert into tabla(nombre, autor, year) values\
    ('"+nombre1+"','"+autor1+"','"+year1+"')"
    print(strConsulta)

    consulta.execute(strConsulta)
    consulta.close()
    db1.commit()
    db1.close()

def consultar():
    db2 = sqlite3.connect("tabla.db")
    print("Estas en la funcion insertar")
    db2row_factory = sqlite3.Row
    consulta = db2.cursor()
    consulta.execute("select * from tabla")
    filas = consulta.fetchall()
    lista = []
    for fila in filas:
        s = {}
        s['nombre'] = fila['nombre']
        s['autor'] = fila['autor']
        s['year'] = str(fila['year'])
        lista.append(s)

    consulta.close()
    db2.close()
    return(lista)


#consultar()

def menu():
    Opcion= input("\nIngresa la opcion deseada\n1.Inserta un valor en la tabla\n2.Consultar los valores de la tabla\n")
    if Opcion==1:
        insertar()
        menu()
    elif Opcion==2:
        ListaNovelas = consultar()
        for novela in ListaNovelas:
            print(novela['nombre'],novela['autor'],novela['year'])
        menu()

menu()
</code></pre>

<blockquote>
  <p>I get this error while testing the second method <code>consultar()</code>.</p>
</blockquote>

<pre><code>$ python file.py

Ingresa la opcion deseada
1.Inserta un valor en la tabla
2.Consultar los valores de la tabla
2
Estas en la funcion insertar
Traceback (most recent call last):
  File "insertar.py", line 56, in &lt;module&gt;
    menu()
  File "insertar.py", line 51, in menu
    ListaNovelas = consultar()
  File "insertar.py", line 33, in consultar
    s['nombre'] = fila['nombre']
TypeError: tuple indices must be integers, not str
</code></pre>

<blockquote>
  <p><code>db2row_factory = sqlite3.Row</code></p>
</blockquote>

<p>This is the problematic line. Instead you meant to set the <code>row_factory</code> factory on the <code>db2</code> connection instance:</p>

<pre><code>db2.row_factory = sqlite3.Row
</code></pre>

<p>Then, all the fetched rows would be now <a href="https://docs.python.org/2/library/sqlite3.html#sqlite3.Row" rel="nofollow"><code>sqlite3.Row</code></a> instances having dictionary-like access to field values.</p>

python sqlite3