Issue with taking input from the COM port - python

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.

Related

how to add new values in sql python if data is already in database?

I have a function to connect to a db and write data to it
The function accepts a list of dictionaries with data
conn = psycopg2.connect(
database="db_database",
user='user',
password='password',
host='127.0.0.1',
)
conn.autocommit = True
cursor = conn.cursor()
get_data = "SELECT * FROM customer_new WHERE login_id = %s;" # Availability check
cursor.execute(get_data, (values_list['login id'],))
last_item = cursor.fetchone()
if last_item == None:
'''If there are NO matches by login_id in the database, then it adds to the database'''
sql = ("""INSERT INTO customer_new (login, telegram_id, orders,
sum_orders, average_check, balance, group_customer, zamena, reg_date, bot_or_site, login_id)
VALUES (%(login)s, %(telegram_id)s, %(orders)s, %(sum_orders)s, %(average_check)s, %(balance)s, %(group)s, %(zamena)s, %(reg_date)s, %(bot_or_site)s, %(login id)s);""")
cursor.execute(sql, values_list)
else:
'''If there are matches in the database, then get the row id and update the data in it'''
item_id_last = last_item[0]
sql = ("""UPDATE customer_new SET (login, telegram_id, orders,
sum_orders, average_check, balance, group_customer, zamena, reg_date, bot_or_site, login_id)
VALUES (%(login)s, %(telegram_id)s, %(orders)s, %(sum_orders)s, %(average_check)s, %(balance)s, %(group)s, %(zamena)s, %(reg_date)s, %(bot_or_site)s, %(login id)s)""")
cursor.execute(sql, [values_list, item_id_last])
conn.close()
I need to write the received data to the database, if the received data is in the database, then they need to be updated.
How to implement it correctly?

I can't either insert or fetch data to sqlite3 database, python

# Create a database or connect to one
conn = sqlite3.connect("tasks_database.db")
# Create the cursor of the database
c = conn.cursor()
# Create Table
c.execute("""CREATE TABLE IF NOT EXISTS tasks (
task_name text
)""")
def query_func():
# Create database or connect to one
connect = sqlite3.connect("tasks_database.db")
# Create Cursor
cursor = connect.cursor()
# Query the database
cursor.execute("SELECT *, oid FROM tasks ")
records = cursor.fetchall()
print(records)
def final_crtb_func():
print("Submit Button Called")
crtb_func()
# Create a database or connect to one
conn = sqlite3.connect("tasks_database.db")
# Create Cursor
c = conn.cursor()
# Insert to Table
c.execute("INSERT INTO tasks VALUES (:task_name)",
{
"task_name": inbox_entry.get()
}
)
# Commit Changes
conn.commit()
# Close Connection
conn.close()
# Create Cursor
c = conn.cursor()
conn.commit()
conn.close()
I called these functions but when I say print records it prints a blank list, although It should have the value of an entry. Any Help?
Note: I made sure that I clicked the button that had the command of the final_crtb_fuc

Python SQLite3 database not saving data Repl.it

I am trying to program an sql database in python that asks for your name and stores it in a database. The problem is that it stores it but then when I reload, the data is gone. Here is the code:
import sqlite3
conn = sqlite3.connect('python.db')
c = conn.cursor()
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS RecordONE (Number REAL, Name TEXT)')
name = input("What is your name?")
def data_entry():
number = "1234"
c.execute("INSERT INTO RecordONE (Number, Name) VALUES(?, ?)", (number, name))
conn.commit()
create_table()
data_entry()
c.close()
conn.close()
What could the problem be?
Thank you
Your problem was that you put con.commit() before you called your functions and actually wrote to the database. Here is a working example:
# Imports
import sqlite3
# Establish connection to database
conn = sqlite3.connect('python.db')
c = conn.cursor()
# Create global variable name
name = ""
def create_table():
global name # Retrieve global variable name
c.execute('CREATE TABLE IF NOT EXISTS RecordONE (Number REAL, Name TEXT)') # DB execution
name = input("What is your name?") # Input to global variable name
def data_entry():
number = "1234"
c.execute("INSERT INTO RecordONE (Number, Name) VALUES(?, ?)", (number, name)) # Execute sql
# Call functions
create_table()
data_entry()
# Save changes to DB
conn.commit()
# Close connection
c.close()
conn.close()
Then you can see the entry you just created in this code:
c.execute('SELECT * FROM RecordONE')
print(c.fetchall())
Hope this was helpful :)

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

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

Categories