Database sqlite3 not updated after deletion python [duplicate] - python

This question already has answers here:
SQLite not saving data between uses
(1 answer)
python sqlite3, how often do I have to commit?
(1 answer)
Closed 1 year ago.
I have a database in python sqlite3 and I'm trying to delete rows from it depending on a value that I selected.
After the execution of this code, I got the result that I want when I'm in this function. But the problem is that when I'm out of this function and try to print the database, the deletion query did not work but the one to add values did. Can anyone understand why?
def datamanip():
selected = SecTree.focus()
values = SecTree.item(selected, 'text')
conn = sqlite3.connect('DataStore.db')
c = conn.cursor()
query='DELETE FROM Limits WHERE TypeCard=(?)'
c.execute(query,(values,))
c.execute("INSERT INTO Limits VALUES (:TypeCard,:CreaseMaxC,:CreaseMinC,:CreaseMaxA,:CreaseMinA,:WidthMaxC,:WidthMinC,:WidthMaxA,:WidthMinA)",
{'TypeCard':values,
'CreaseMaxC': w2data,
'CreaseMinC': wdata,
'CreaseMaxA': w4data,
'CreaseMinA': w3data,
'WidthMaxC': w6data,
'WidthMinC': w5data,
'WidthMaxA': w8data,
'WidthMinA': w7data
}
)
c.execute('SELECT * FROM Limits')
records= c.fetchall()
print(records)
EDIT:
The connection must be commited after making the deletion for the database.
conn.commit()
solved the problem.

Related

Why would a MySQL DELETE statement fail when the corresponding SELECT statement works? [duplicate]

This question already has answers here:
Python mySQL Update, Working but not updating table
(3 answers)
Closed 3 months ago.
I have a MySQL database instance hosted on GCP, and I am connecting to it using the pymysql python package. I would like to delete some rows from a database table called Basic.
The code I have written to do this is included below. The variable conf contains the connection details to the database instance.
import pymysql
import pandas as pd
# Establish connection.
connection = pymysql.connect(**conf)
cursor = connection.cursor()
# Delete rows of table.
try:
cursor.execute("DELETE FROM Basic WHERE Date = '2022-11-25 04:00:00';")
except Exception as ex:
print("Exception occured: %s" %ex)
finally:
connection.close()
# Check the table to see if deletion has occurred.
connection = pymysql.connect(**conf)
cursor = connection.cursor()
cursor.execute("SELECT * FROM Basic WHERE Date = '2022-11-25 04:00:00'")
connection.close()
df = pd.DataFrame(cursor.fetchall(), columns = ["Date", "State", "Price", "Demand"])
Clearly one would expect the dataframe defined here to have no rows, but this is not the case. This shows that the SELECT statement included in the code above produces the expected result, but the corresponding DELETE statement does not.
Why is this the case?
The code above requires the addition of the following line, in order to commit the DELETE statement.
connection.commit()
The commit method should be called after every transaction that modifies data, such as this one.

My data doesn't show up on DB Browser for SQLite [duplicate]

This question already has answers here:
Sqlite insert query not working with python?
(2 answers)
Closed 1 year ago.
I am currently learning SQL for one of my projects and the site, that I learn from, advised me to use DB Browser to see my Database Content. However, I can't see the data inside the SQL. This is how my code looks like. I'm creating a table and then trying to write some values in it. It creates the DB successfully but the data doesn't show up.
import sqlite3 as sql
connection = sql.connect("points.db")
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS servers (server_id TEXT, name TEXT, exp INTEGER)")
cursor.execute("INSERT INTO servers VALUES ('848117357214040104', 'brknarsy', 20)")
Can you check that your data is inserted?
Something like this in the end:
cursor.execute("SELECT * FROM servers")
r = cursor.fetchall()
for i in r:
print(r)
Perhaps SQLite browser just needs a refresh

Printing SQL string as argument of a cursor object [duplicate]

This question already has answers here:
Python SQLite how to get SQL string statement being executed
(4 answers)
Closed 2 years ago.
Here I see the suggested way of building queries with python and sqlite3:
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())
How do I print the query instead of the result? I know it's not a string, and so a "print sql" statement wouldn't work. In my case, I am running flask and I want to have this code responding to an API invocation:
...
cur = conn.cursor()
arguments = (username, password, )
query = 'SELECT * FROM logins where ((username = ?) AND (password = ?));', arguments
return(query)
...
I would expect to see this query, not to execute it. However, I receive this output:
ValueError: too many values to unpack (expected 2)
Furthermore, I didn't see any method that exports the last query issued in the SQLite.
This might not be the answer you're looking for, but you can format the query as a string using python string format and print, before formatting again using db-api within the c.execute() statement. As long as you only format the executed query with db-api, you're not at risk from sql injection.

Using a function to get column names Sqlite3 [duplicate]

This question already has answers here:
Is there a way to get a list of column names in sqlite?
(13 answers)
Closed 6 years ago.
I have a short question for one of my classes; it involves building a function in python that takes a sqlite database name and a table name as arguments, and returns the column names inside this table.
So far I have done the following:
#!/user/bin/env python
import sqlite3
import pprint
pp = pprint.PrettyPrinter()
def print_table_columns(database_name, table_name):
conn = sqlite3.connect(database_name)
c = conn.cursor()
c.execute('SELECT sql FROM sqlite_master WHERE type=\'table\' AND name=\'table_name\'')
print c.fetchall()
conn.close()
Sadly, this code produces an empty list. I suspect that the SQL command inside the execute function does not take variables defined in Python, but I am not sure. Any help on this would be much appreciated.
Sure, you need to parameterize the query:
c.execute("""
SELECT
sql
FROM
sqlite_master
WHERE
type = 'table' AND
name = ?""", (table_name, ))
where ? is a placeholder that sqlite3 would fill with the query parameter (table_name here).

How to Python PostgreSQL INSERT IF NOT EXIST? [duplicate]

This question already has answers here:
How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?
(7 answers)
Closed 7 years ago.
I have a python script that is using the Psycopg adapter; I am parsing a JSON Array and inserting into my PostgreSQL database.
for item in data["SchoolJSONData"]:
mId = item.get("Id")
mNumofRooms = item.get("NumofRooms")
mFloors = item.get("Floors")
con = None
con = psycopg2.connect("dbname='database' user='dbuser'")
cur = con.cursor()
cur.execute('INSERT INTO Schools(Id, NumofRooms, Floors)VALUES(%s, %s, %s)',(mId, mNumofRooms, mFloors))
con.commit()
Everytime I run the script again, I get the following:
psycopg2.IntegrityError: duplicate key value violates unique constraint "schools_pkey"
How can I run the insert script so that it will ignore existing entries in the database?
EDIT: Thanks for the replies all... I am trying to NOT overwrite any data, only ADD (if the PK is not already in the table), and ignore any errors. In my case I will only be adding new entries, never updating data.
There is no single one way to solve this problem. As well this problem has little to do with python. It is valid exception generated by the database ( not just postgre all databases will do the same ).
But you can try - catch this exception and continue smoothly later.
OR
you can use "select count(*) where id = mId" to ensure it is not existing already.

Categories

Resources