Question

I have created a script that finds the last value in the first row of my database

import sqlite3
global SerialNum
conn = sqlite3.connect("MyFirstDB.db")
conn.text_factory = str
c = conn.cursor()
SerialNum = c.execute('select Serial from BI4000 where Serial in (Select max(Serial) from BI4000)')
print SerialNum
conn.commtt()
conn.close()

the program prints the result

[('00003',)]

which is the last result in the current database, all the data that will be entered into the final database will be serial numbers and so it will be in order.

My question is can I remove all the quotations/brackets/comma as I wish to asign this value to a variable.

The program that I wish to make is a testing system that adds new entries to the database, I wish to check what the last entry is in the database so the system can continue the entries from that point.

Était-ce utile?

La solution

The result of the query you execute is being represented as a Python list of Python tuples.

The tuples contained in the list represent the rows returned by your query.

Each value contained in a tuple represents the corresponding field, of that specific row, in the order you selected it (in your case you selected just one field, so each tuple has only one value).

Long story short: your_variable = SerialNum[0][0]

Autres conseils

If you want to retrieve just one column from one row, use:

c.execute('select Serial from BI4000 where Serial in (Select max(Serial) from BI4000)')
result = c.fetchone()
if result:  # first row returned?
    print result[0]  # first column

Your query could be simplified to:

c.execute('Select max(Serial) from BI4000')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top