简体   繁体   English

无法从SQLITE3数据库中获取最后一行ID

[英]Can't get the last row id from SQLITE3 database

I have a script that asks for input, and that input is then inserted into a table. 我有一个要求输入的脚本,然后将该输入插入到表中。 The next time the script is run, I'd like for it to tell the user what id the last input has. 下次运行脚本时,我希望它告诉用户最后一个输入有什么ID。

The table looks like: id INTEGER PRIMARY KEY AUTOINCREMENT, userid TEXT, domain TEXT, password TEXT, webserver TEXT, sqlserver TEXT 该表如下所示: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 the following text: instead of the id from the last row. 我被告知我可以使用来自SQLITE_SEQUENCE WHERE name ='table_name'的SELECT seq,但它会产生以下文本:而不是最后一行的id。

Please note that I'm an extremely new Python / SQLite3 coder! 请注意,我是一个非常新的Python / SQLite3编码器!

For your reference, the code sofar looks like this: 供您参考,代码sofar如下所示:

#!/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 ##########

The SQL statement SELECT max(id) FROM table_name should give you the maximum id. SQL语句SELECT max(id) FROM table_name应该为您提供最大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: 编辑:在python中获取实际值意味着从游标中读取它:

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, ie the max(id). fetchone()将select语句中的第一行作为元组返回(除非使用了row_factory),因此在这种情况下, fetchone()[0]将返回第一个(并且只有)第一列(且仅) row,即max(id)。

See http://docs.python.org/2/library/sqlite3.html for more info. 有关详细信息,请参阅http://docs.python.org/2/library/sqlite3.html

尝试使用sqlite3_last_insert_rowid()

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM