Can't get last row id

Question:

I have a script that asks for input that is inserted into a table. The next script run I’d like it to tell the user what id the last input has. The table:

id INTEGER PRIMARY KEY AUTOINCREMENT, userid TEXT, domain TEXT, password TEXT, webserver TEXT, sqlserver TEXT

I was told I could use SELECT seq from SQLITE_SEQUENCE WHERE name='table_name' but it yields <sqlite3.Cursor object at 0x7f367c201500> instead of the id from the last row:

#!/usr/bin/python
import os, sys, sqlite3
######## CHECK SYSTEM COMPATIBILITY ########
if os.name =='posix':
    os.system("clear")#CLEAR SCREEN#
    pass
else:
    sys.exit("Operating System is not supported")
######## END CHECK SYSTEM COMPATIBILITY ########
######## CHECK IF SCRIPT IS RUN AS ROOT ########
#if os.geteuid() != 0:
#       sys.exit("Script must be run as root")
#else:
#       pass
####### END CHECK IF SCRIPT IS RUN AS ROOT ########
####### CREATE DATABASE AND CHECK IF TABLE EXISTS ##########
conn = sqlite3.connect("dat.db")
c = conn.cursor()
c.execute ('''CREATE TABLE IF NOT EXISTS kunder
            (id INTEGER PRIMARY KEY AUTOINCREMENT, userid TEXT, domain TEXT, password      TEXT, webserver TEXT, sqlserver TEXT)''')
conn.commit()
print c.execute ("SELECT seq from SQLITE_SEQUENCE WHERE name='kunder'")
conn.close()
######## DONE CREATE DATABASE AND CHECK IF TABLE EXISTS #########
###### ASK FOR INPUT ##########
########### HERE NEEDS TO BE A CHECK TO DETERMINE THE LATEST USERID - ALSO NEEDS TO BE    FOR WEBSERVER AND PASSWORD #################
userid = raw_input("Enter userid: ")
########### HERE NEEDS TO BE A CHECK TO SEE IF USERID EXISTS!!!!!#####################
domain = raw_input("Enter domain: ")
password = raw_input("Enter password: ")
########### NEEDS TO BE A WAY TO AUTOGENERATE A PASSWORD!!! ####################
webserver = raw_input("Enter webserver: ")
sqlserver = raw_input("Enter sqlserver: ")
###### FINISHED ASK FOR INPUT #######
######## DATABASE ###########
conn = sqlite3.connect("dat.db")
c = conn.cursor()
c.execute ("INSERT INTO kunder (userid, domain, password, webserver, sqlserver) VALUES    (?,?,?,?,?)", (userid, domain, password, webserver, sqlserver))
conn.commit()
conn.close()
####### DONE WITH DATABASE ##########
Asked By: MadsRC

||

Answers:

Try using sqlite3_last_insert_rowid()

Answered By: Susitha

The SQL statement SELECT max(id) FROM table_name should give you the maximum id. If you’re auto-incrementing then this would be the same as the last inserted.

Edit: To get the actual value in python means reading it from the cursor:

cursor = sqlite3.execute('SELECT max(id) FROM table_name')
max_id = cursor.fetchone()[0]

fetchone() returns the first row from the select statement as a tuple (unless a row_factory is used), so fetchone()[0] will, in this case, return the first (and only) column in the first (and only) row, i.e. the max(id).

See http://docs.python.org/2/library/sqlite3.html for more info.

Answered By: aquavitae

You could use Cursor.lastrowid to get the last inserted row.

This read-only attribute provides the rowid of the last modified row. It is only set if you issued an INSERT or a REPLACE statement using the execute() method. For operations other than INSERT or REPLACE or when executemany() is called, lastrowid is set to None.

If the INSERT or REPLACE statement failed to insert the previous successful rowid is returned.

The last statement is something to be mindful about. If there’s no sqlite3.Error throws, then referring lastrowid is appropriate.

Here’s an example:

import sqlite3

data_person_name = [('Michael', 'Fox'),
                    ('Adam', 'Miller'),
                    ('Andrew', 'Peck'),
                    ('James', 'Shroyer'),
                    ('Eric', 'Burger')]

con = sqlite3.connect(":memory:")
c = con.cursor()

c.execute('''CREATE TABLE q1_person_name
             (name_id INTEGER PRIMARY KEY,
              first_name varchar(20) NOT NULL,
              last_name varchar(20) NOT NULL)''')

for data_person in data_person_name:
    c.execute('INSERT INTO q1_person_name(first_name, last_name) VALUES (?,?)', data_person)
    # get the last rowid inserted
    last_name_id = c.lastrowid
    print(last_name_id)
Answered By: Yiakratovic
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.