I'm trying to insert some data into SQL database, and the problem is that I'm really green on this. So the MAIN problem is that How can I sort all the items in table? I have 3 main things: ID, CARNUM, TIME. But in this 'Insertion' I have to type the id manually. How can I make that the system would create a numeric id numeration automatically?
Here's the insertion code:
postgres_insert_query = """ INSERT INTO Vartotojai (ID, CARNUM, TIME) VALUES (%s,%s,%s)"""
record_to_insert = (id, car_numb, Reg_Tikslus_Laikas)
cursor.execute(postgres_insert_query, record_to_insert)
connection.commit()
count = cursor.rowcount
print (count, "Record inserted successfully into mobile table")
pgadmin sort
pgadmin table
You could change the datatype of ID to serial, which is an auto incrementing integer. Meaning that you don't have to manually enter an ID when inserting into the database.
Read more about datatype serial: source
Related
Okay so i have a table which has student id and the student id is used as identifier to edit the column but what if the same student lends a book twice then all the student value will b edited which i don't want....i want the last entered data of student id to b edited and using a Sl.No is not a solution here because its practically complicated.I am using python connector. Please help :) Thanks in advance
code i use right now :
con = mysql.connect(host='localhost', user='root',
password='monkey123', database='BOOK')
c = con.cursor()
c.execute(
f"UPDATE library set `status`='Returned',`date returned`='{str(cal.selection_get())}' WHERE `STUDENT ID`='{e_sch.get()}';")
c.execute('commit')
con.close()
messagebox.showinfo(
'Success', 'Book has been returned successfully')
If I followed you correctly, you want to update just one record that matches the where condition. For this to be done in a reliable manner, you need a column to define the ordering of the records. It could be a date, an incrementing id, or else. I assume that such column exists in your table and is called ordering_column.
A simple option is to use ORDER BY and LIMIT in the UPDATE statement, like so:
sql = """
UPDATE library
SET status = 'Returned', date returned = %s
WHERE student_id = %s
ORDER BY ordering_column DESC
LIMIT 1
"""
c = con.cursor()
c.execute(sql, (str(cal.selection_get()), e_sch.get(), )
Note that I modified your code so input values are given as parameters rather than concatenated into the query string. This is an important change, that makes your code safer and more efficient.
I have a sqlite3 program in which I have to connect to a database stored in 'employees.db'. I will enter the first name, last name and salary and then print it. For printing, I will use fetchall(). But when I print the output, what I get is this-->
[]
only 2 square brackets?
What is wrong?
I have started to learn python 2 weeks ago. But my course where I am learning is going too fast. I don't know what I am doing in this program is the correct approach or not?
HERE IS MY CODE--->>>
import sqlite3;
conn=sqlite3.connect('employees.db');
c=conn.cursor();
c.execute("""CREATE TABLE employees(first text,last text,pay integer)""");
c.execute("INSERT INTO employees VALUES('Tendo','Sinha',600000)");
c.execute("INSERT INTO employees VALUES('Krit','Kumar',40000)");
print(c.fetchall());
conn.commit();
conn.close
I don't get any error. The output only shows:-
[]
Only 2 square brackets.
You are inserting rows into the table but not retrieving them at all.
Try adding a SELECT statement:
import sqlite3
conn = sqlite3.connect("employees.db")
c = conn.cursor()
# Create table, insert things...
c.execute(
"""CREATE TABLE IF NOT EXISTS employees(first text,last text,pay integer)"""
)
c.execute("INSERT INTO employees VALUES('Kritin','Sinha',600000)")
c.execute("INSERT INTO employees VALUES('Krit','Kumar',40000)")
# Commit the changes.
conn.commit()
# Retrieve from the table.
c.execute("SELECT * FROM employees")
print(c.fetchall())
you have to run a query for fetching all rows.
add these lines to your code-
data = c.execute("Select * FROM employees").fetchall()
print(data);
I am working on a small project where I need to insert the value into different tables based on the Slave Id,
for example, if the user is sending multiple values with slave id 1 I need to insert the value in the table "Instant_Values_S1" and if the slave id 2 I need to insert the value into "Instant_Values_S2"
this is my code:
c.execute("INSERT INTO Instant_Values_S1 VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
1,
utctime,
data[0],
data[1],
data[2],
data[3],
data[4],
data[5],
data[6],
data[7],
data[8],
data[9],
data[10],
data[11],
data[12],
data[13],
data[14],
))
conn.commit()
conn.close()
here I define the table name again and again but instead, I wanna give those automatically? can someone help me out!
Thanks
AFAIK, this is a know limitation of SQL: you can use parameters for values, but not for table or columns names. But a SQL command is just a string and you can use Python to build the static part of the request. More or less:
table_names = [None, "Instant_Values_S1", "Instant_Values_S2" ]
# will raise exception if slave_id is not 1 or 2
req = "INSERT INTO " + table_names[slave_id] + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
c.execute(req, (slave_id, ...)
I'm attempting to update my sqlite db with 2 python lists. I have a sqlite db with three fields. Name, number, date. I also have three python lists with similar names. I'm trying to figure out a way to update my sqlite db with data from these 2 lists. I can get the db created, and even get a single column filled, but I cant seem to update it correctly or at all. Is there a way to INSERT both lists at once? Rather than INSERT a single column and then UPDATE the db with the other?
Here is what I have so far:
name_list = []
number_list = []
date = now.date()
strDate = date.strftime("%B %Y")
tableName = strDate
sqlTable = 'CREATE TABLE IF NOT EXISTS ' + tableName + '(name text, number integer, date text)'
c.execute(sqlTable)
conn.commit()
for i in name_list:
c.execute('INSERT INTO January2018(names) VALUES (?)', [i])
conn.commit()
I can't seem to get past this point. I still need to add another list of data (number_list) and attach the date to each row.
Here's what I have on that:
for i in number_list:
c.execute('UPDATE myTable SET number = ? WHERE name', [i])
conn.commit()
Any help would be much appreciated. And if you need more information, please let me know.
You can use executemany with zip:
c.executemany('INSERT INTO January2018 (name, number) VALUES (?, ?)', zip(name_list, number_list))
conn.commit()
I wasn't sure how to word this question appropriately. My problem here is i am using the PySerial package to read values from a port and am sending 5 values to a list. I have a condition where when the value 10000 shows, send a timestamp to a database, i want that to happen but not to add that value to the list. here is the code.
while i<5:
data=ser.readline().strip()
print data
i=i+1
if int(data)<30:
frame = cap.read()[1]
pic = str(frame)
cursor.execute("CREATE TABLE if not exists Camera (ID INT NOT NULL AUTO_INCREMENT,img BLOB,PRIMARY KEY(ID))")
cursor.execute("INSERT INTO Camera (img) VALUES(%s)",(pic,))
conn.commit()
cv2.imwrite(filename='img.jpg', img=frame)
arduinoData.append(data)
elif int(data)==10000:
cursor.execute("INSERT INTO Alarm (time) VALUES(now())")
print("Inserted",cursor.rowcount,"row(s) of data.")
arduinoData.append("4")
else:
arduinoData.append(data)
#Drop previous table of same name if one exists
cursor.execute("DROP TABLE IF EXISTS SensorData;")
print("Finished dropping table (if existed).")
# Create table
cursor.execute("CREATE TABLE SensorData (ID INT NOT NULL AUTO_INCREMENT,value VARCHAR(40),PRIMARY KEY(ID));")
print("Finished creating Sensor table.")
# Insert some data into table
cursor.executemany("INSERT INTO SensorData (value) VALUES (%s), (%s), (%s), (%s), (%s);",[arduinoData])
to try and solve the problem for now when the value 10000 is detected I am appending the value '4' to the list so I won't get an SQL exception error for not inputting 5 values from the list into the database. Can anyone help with this?