sqlite3 remove brackets from printed data

做~自己de王妃 提交于 2020-07-18 03:05:09

问题


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.


回答1:


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]




回答2:


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')


来源:https://stackoverflow.com/questions/23040236/sqlite3-remove-brackets-from-printed-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!