Can't get the last row id from SQLITE3 database - python

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.
The table looks like: 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.
Please note that I'm an extremely new Python / SQLite3 coder!
For your reference, the code sofar looks like this:
#!/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. 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.

Try using 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)

Related

Issue with taking input from the COM port

I am trying to make it so that when a certain number comes through the COM port it updates a value within my sql table as can be seen in the code below
import sqlite3
import serial
def get_attendance_status():
# Connect to the database
conn = sqlite3.connect('attendance.db')
c = conn.cursor()
# Select all rows from the 'students' table
c.execute("SELECT * FROM students")
# Fetch all rows from the cursor
rows = c.fetchall()
# Close the connection to the database
conn.close()
# Return the rows
return rows
def mark_student_present(serial_number):
# Connect to the database
conn = sqlite3.connect('attendance.db')
c = conn.cursor()
# Update the attendance status for the student with the given serial number
c.execute("UPDATE students SET attendance_status = 'present' WHERE serial_number = ?", (serial_number,))
# Commit the changes to the database
conn.commit()
# Close the connection to the database
conn.close()
def create_database_and_table():
# Connect to the database
conn = sqlite3.connect('attendance.db')
c = conn.cursor()
# Create the table if it doesn't already exist
c.execute('''CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
serial_number CHAR(10) UNIQUE,
name VARCHAR(255),
attendance_status VARCHAR(255)
)''')
# Reset the attendance status of all students to 'absent'
c.execute("UPDATE students SET attendance_status = 'absent'")
# Add the students to the table if they don't already exist
c.execute("INSERT OR IGNORE INTO students (serial_number, name, attendance_status) VALUES (?, ?, ?)", (1, 'Declan', 'absent'))
c.execute("INSERT OR IGNORE INTO students (serial_number, name, attendance_status) VALUES (?, ?, ?)", (2, 'Milan', 'absent'))
# Commit the changes to the database
conn.commit()
# Close the connection to the database
conn.close()
def main():
# Create the database and table if they don't already exist
create_database_and_table()
# Open the serial port
ser = serial.Serial('COM5', 115200)
# Continuously read serial numbers from the serial port and mark the corresponding students as present
while True:
# Read a line of input from the serial port
serial_number = ser.readline()
# Check if the user entered "exit" on the command line
if serial_number.lower() == 'exit':
break
# Mark the student as present
mark_student_present(serial_number)
# Get the attendance status for all students
rows = get_attendance_status()
# Print the attendance status for each student
for row in rows:
serial_number = row[1]
name = row[2]
attendance_status = row[3]
print(f'{name} ({serial_number}): {attendance_status}')
if __name__ == '__main__':
main()
However when I run the scrip I get this error
TypeError: mark_student_present() missing 1 required positional argument: 'serial_number'
[Done] exited with code=1 in 0.113 seconds
I want it to continuously check the com port to see if the numbers relating to the sql table are recieved. If they are recieved it should then change the attendance_status value.

sorry for that kind of question but i must ask . How to create a table in SQLITE to ask me what to call a table

E.g. After launching the program:
It is in interactive mode
We are asked what name we want to create the database with;
After creating the database, the program asks us under what name to create the table in the database;
In the next step, the program asks us how many columns the table should have;
Enter the names of the mentioned number of columns and their types interactively;
Finally, create a database and a table with the columns indicated in it;
import sqlite3
connection = sqlite3.connect(input("Enter the name for base: "))
cursor = connection.cursor()
table_name = input("Enter the name for table: ")
columns_name = []
columns_amount = int(input("Enter amount of coulms and name them: "))
for item in range(columns_amount):
item = input("input theme mane of column: ")
columns_name.append(item)
cursor.execute("DROP TABLE IF EXISTS "+table_name+"" )
cursor.execute("CREATE TABLE IF NOT EXISTS "+ table_name +" ("+columns_name[0]+" INTEGER PRIMARY KEY AUTOINCREMENT ,Name TEXT, "+columns_name[1]+" TEXT, "+columns_name[2]+" TEXT, "+columns_name[3]+" TEXT )")
connection.commit()
You can just create the sql string for table creation inside the loop like -
import sqlite3
connection = sqlite3.connect(input("Enter the name for database: "))
cursor = connection.cursor()
table_name = input("Enter the name for table: ")
sql_string = "CREATE TABLE IF NOT EXISTS {} (".format(table_name)
columns_amount = int(input("Enter amount of columns: "))
for i in range(columns_amount):
column = input("input the name of column {}: ".format(i + 1))
datatype = input("input the type of column: ")
# You may want to check here whether column name and data type is valid or not
sql_string += "{} {},".format(column, datatype)
# remove the last extra comma
sql_string = sql_string[:-1]
sql_string += ")"
print(sql_string)
cursor.execute("DROP TABLE IF EXISTS {}".format(table_name))
# Finally create the table
cursor.execute(sql_string)
connection.commit()
Your code will not work because during table creation you are assuming that there are 3 columns which may not be true. So accessing those indices of columns_name might throw exception.

Unexpected output of weird characters for Python sqlite3 database

My python 3.6 code is supposed to create a database and create a table inside it.
import sqlite3
db_filename = 'database.db'
connect = sqlite3.connect(db_filename)
c = connect.cursor()
c.execute('CREATE TABLE IF NOT EXISTS task (id number PRIMARY KEY, priority integer, details text, status text)')
connect.commit()
connect.close()
However the output is not what I intended. I am getting weird characters included in the .db file;
SQLite format 3  # .�
� b b� k�9tabletasktaskCREATE TABLE task (id number PRIMARY KEY, priority integer, details text, status text)'; indexsqlite_autoindex_task_1task


If anyone could tell me where I went wrong I would be grateful.
Thanks.
There is nothing wrong here. To view a .db file you need db viewer or reader tool. http://sqlitebrowser.org/ has DB browser for SQLite which can be used to view your database. You can install it and use it to read your .db file.
If you want to use the table you can do so by inserting elements in the table and viewing it as follows:
import sqlite3
db_filename = 'database.db'
connect = sqlite3.connect(db_filename)
c = connect.cursor()
c.execute('CREATE TABLE IF NOT EXISTS task (id number PRIMARY KEY, priority integer, details text, status text)')
c.execute("INSERT INTO task (id,priority,details,status) \
VALUES (1,22,'ABC','YES' )");
cursor = c.execute("SELECT id,priority,details,status from task")
for row in cursor:
print ("ID = ", row[0])
print ("PRIORITY = ", row[1])
print ("DETAILS = ", row[2])
print ("STATUS = ", row[3], "\n")
connect.commit()
connect.close()
OUTPUT:
ID = 1
PRIORITY = 22
DETAILS = ABC
STATUS = YES

How to initialize a database just once on Python using SQLite 3?

I'm trying to make a python app where the user can add a row to a table and visualize all the rows. My problem is that it seems that every time I run the program, the database is created again, with no values. I say this because there is an autoincrement value that is always the same. When I write the program again on the cmd and insert the values by hand it does show me more than one value.
Here's the code:
import sqlite3
conn = sqlite3.connect("amigo_local_db.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS images (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT, bash TEXT)")
action = int(input("Insert an action: (1: Add row | 2: Close)"))
if(action == 1):
url = input("URL: ")
bash = input("BASH: ")
values = (url,bash)
c.execute("INSERT INTO images VALUES(null,?,?)",values)
else:
conn.close()
quit()
for row in c.execute("SELECT * FROM images"):
print(row)
conn.close()
You need to commit the INSERT transaction before closing, or it will not be persisted:
import sqlite3
conn = sqlite3.connect("amigo_local_db.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS images (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT, bash TEXT)")
action = int(input("Insert an action: (1: Add row | 2: Close)"))
if(action == 1):
url = input("URL: ")
bash = input("BASH: ")
values = (url,bash)
c.execute("INSERT INTO images VALUES(null,?,?)",values)
conn.commit()
else:
conn.close()
quit()
for row in c.execute("SELECT * FROM images"):
print(row)
conn.close()

PRAGMA foreign key error (Python)

Going to paste in the entire file because I have absolutely no idea how to fix my issue;
import sqlite3
import time
import datetime
import sys
conn = sqlite3.connect('offerdatabase1.db')
c = conn.cursor()
c.execute('PRAGMA foreign_keys = ON')
############################# Creating the Database Tables #############################
# Creating the 'Odds' Table
def create_odds_table():
c.execute("""CREATE TABLE IF NOT EXISTS Odds(OddsID INTEGER PRIMARY KEY,
TeamSelection TEXT,
BackOdds INTEGER,
LayOdds INTEGER)
""")
c.execute('PRAGMA foreign_keys = ON')
# # # Creating the 'Value' Table # # #
def create_value_table():
c.execute("""CREATE TABLE IF NOT EXISTS Value(ValueID INTEGER PRIMARY KEY,
BackStake INTEGER,
LayStake INTEGER,
Liability INTEGER,
NetValue INTEGER)
""")
c.execute('PRAGMA foreign_keys = ON')
# Creating the 'User' Table
def create_user_table():
c.execute("""CREATE TABLE IF NOT EXISTS User(UserID INTEGER PRIMARY KEY,
FirstName TEXT,
LastName TEXT,
Email TEXT,
Date TEXT,
Time TEXT)
""")
c.execute('PRAGMA foreign_keys = ON')
# Creating the 'Offer' Table
def create_offer_table():
c.execute("""CREATE TABLE IF NOT EXISTS Offer(OfferID INTEGER PRIMARY KEY,
OfferType TEXT,
OfferDesc TEXT,
Bookmaker TEXT,
Exchange TEXT,
OddsID INTEGER,
ValueID INTEGER,
UserID INTEGER,
FOREIGN KEY(OddsID) REFERENCES Odds(OddsID),
FOREIGN KEY(ValueID) REFERENCES Value(ValueID),
FOREIGN KEY(UserID) REFERENCES User(UserID))""")
c.execute('PRAGMA foreign_keys = ON')
# Running the Subroutines, in order to create the database with tables previously stated.
if __name__ == "__main__":
db_name = ('offerdatabase1.db')
c.execute('PRAGMA foreign_keys = ON')
create_odds_table()
create_value_table()
create_user_table()
create_offer_table()
############################# Inserting Data into Tables #############################
def data_entry_odds():
print('==================== Odds and Team Selection ====================')
TeamSelection = input('Team you selected: ')
BackOdds = input('Back Bet Odds: ')
LayOdds = input('Lay Bet Odds: ')
c.execute("INSERT INTO Odds (TeamSelection, BackOdds, LayOdds) VALUES (?, ?, ?)",
(TeamSelection, BackOdds, LayOdds))
c.execute('PRAGMA foreign_keys = ON')
conn.commit()
def data_entry_value():
print('================ Stakes, Liability and Net Value ================')
BackStake = input('Stake on Back Bet: ')
LayStake = input('Stake on Lay Bet: ')
Liability = input('Liability (applies only with exchange): ')
NetValue = input('Net value : ')
c.execute("INSERT INTO Value (BackStake, LayStake, Liability, NetValue) VALUES (?, ?, ?, ?)",
(BackStake, LayStake, Liability, NetValue))
c.execute('PRAGMA foreign_keys = ON')
conn.commit()
def data_entry_user():
print('======================== User Information =======================')
FirstName = input('Firstname: ')
LastName = input('Surname: ')
Email = input('Email Address: ')
Date = time.strftime("%d/%m/%Y")
Time = time.strftime("%H:%M")
c.execute("INSERT INTO User (FirstName, LastName, Email, Date, Time) VALUES (?, ?, ?, ?, ?)",
(FirstName, LastName, Email, Date, Time))
c.execute('PRAGMA foreign_keys = ON')
conn.commit()
def data_entry_offer():
print('======================= Offer Information =======================')
OfferType = input('Type of Offer: ')
OfferDesc = input('Offer Description: ')
Bookmaker = input('Name of Bookmaker: ')
Exchange = input('Name of Exchange: ')
c.execute("INSERT INTO Offer (OfferType, OfferDesc, Bookmaker, Exchange) VALUES (?, ?, ?, ?)",
(OfferType, OfferDesc, Bookmaker, Exchange))
c.execute('PRAGMA foreign_keys = ON')
conn.commit()
########################### Text Based User Interface ###########################
def rootchoice():
userchoice = input('Would you like to track a bet? (Y - Yes, N - No) ')
if userchoice.upper() == 'Y':
yeschoice()
elif userchoice.upper() == 'N':
nochoice()
else:
print('*ERROR* - Please enter either \'Y\' or \'N\' (no other characters accepted)')
rootchoice()
def yeschoice():
data_entry_user()
data_entry_offer()
data_entry_odds()
data_entry_value()
print('Data entry complete, recorded successfully.')
loopchoice()
def nochoice():
print('Thank you for using James\' Betting Tracker, goodbye!')
sys.exit()
def loopchoice():
loopuserchoice = input('Would you like to track another bet? (Y - Yes, N - No) ')
if loopuserchoice.upper() == 'Y':
yeschoice()
elif loopuserchoice.upper() == 'N':
nochoice
else:
print('*ERROR* - Please enter either \'Y\' or \'N\' (no other characters accepted)')
loopchoice()
print('Welcome to James\' Betting Tracker!')
rootchoice()
Excuse the annotation and ridiculous headings, I am writing this code for a school project. After reading around the subject of foreign keys within sqlite3, I stumbled across the command;
PRAGMA foreign_keys = ON
After reading around about it, I was told that you had to set PRAGMA foreign_keys to ON everytime a database connection was made.
I've done this, but the foreign keys still don't work with my database.
Any help would be greatly appreciated, i'm incredibly new to the world of python and programming in general, thanks!
Foreign key constraints are called "constraints" because they are constraints, i.e., the constrain the values in the database. In other words, they prevent you from inserting values that would violate the rules.
In this case, you would get an error if you tried to insert an invalid OddsID, ValueID or UserID number (one that does not exist in the parent table) into the Offers table.
But you never do that; you leave those columns empty.
It is not possible for the database to automatically insert a reference to a row in the parent table – which of those rows should it choose?
If your data model requires that all Offers rows have valid references to the other three tables, add NOT NULL constraints to those columns.

Categories