I have been reading a number of threads on how to accomplish this but for some reason it is not working.
I need to delete a Row from a database using a string variable from an entry widget as the "WHERE (variable name)=" is used in the DB query.
The entry widget data is stored as Snippet_Name and the same name is being used as a column name in the DB.
The database has 7 columns but I am only using the 1 column for the query and I want to delete the complete row which contains the entry variable. I have tried variations of DELETE with no success.
The code being used is:
def delete_code():
try:
snippetname = Snippet_Name.get()
sql_delete_query = ('DELETE FROM Code WHERE Snippet_Name = "?"', (snippetname))
c.execute(sql_delete_query)
conn.commit()
except:
messagebox.showerror('PYSnippet', 'Failed to delete record')
A little help and hint would be appreciated.
I went over the query and found 2 errors that needed to be address to correct the problem. The first problem was I had the ? enclosed in quotations which should not be there. Second problem was forgetting to a comma to the variable.
def delete_code():
try:
snippetname = Snippet_Name.get()
sql_delete_query = ('DELETE FROM Code WHERE Snippet_Name = ?' (snippetname,))
c.execute(sql_delete_query)
conn.commit()
except:
messagebox.showerror('PYSnippet', 'Failed to delete record')
Related
import sqlite3 ,csv
with open("BollywoodMovieDetail.csv","r")as file:
no_records = 0
for row in file:
c.execute("INSERT INTO Movie VALUES(?,?,?,?,?,?,?,?,?,?)", row.split(","))
conn.commit()
no_records += 1
conn.close()
print('\n{} Records Transferred'.format(no_records))
i dont know why the code is terminating my guess is that their is cell which have "," in it amd cousing problem. If it is so please let me know how to fix it. I m new to SQLITE3 so its getting hectic
Your insert statement expects 10 values per record. The error message implies that one or more lines has 11 values after splitting by comma, or, alternatively, one or more lines have 10 commas. You may iterate over your file and try to find the offending line(s):
with open("BollywoodMovieDetail.csv", "r") as file:
for row in file:
parts = row.split(",")
if len(parts) == 11:
print(row)
So I'm trying to move my csv files from the source folder to the dest folder after performing an action on each file using nested for loops
Below are the nested for loops.
What's happening now is that the top file gets copied into the table in the database, but it doesn't get moved to destination folder after its contents are inserted into the sql table, and then the loop breaks after first run and prints the error in try block.
If I remove the shutil statement, all rows from each csv file successfully copies into database.
Essentially I want that to happen, but I also want to move each file, after I've copied all the data into the table, to the dest folder.
This script will be triggered on a power automate action that will run once a file is added to the folder. So I don't want to add/duplicate the rows in my database from the same file.
I'm also adding variables below this code so you can get an idea of what the function is doing as well.
Thanks for any help you can provide on this, and let me know if more clarification is needed.
My attempt:
for file in dir_list:
source = r"C:\Users\username\source\{}".format(file)
df = pd.read_csv(path2)
df = df.dropna()
rows= df_to_row_tuples(df)
for row in rows:
cursor.execute(sql, row)
conn.commit()
shutil.move(source, destination)
Variables:
def df_to_row_tuples(df):
df = df.fillna('')
rows = [tuple(cell) for cell in df.values]
return rows
conn = sqlite3.connect(r'C:\Users\some.db')
cursor = conn.cursor()
sql = "INSERT INTO tblrandomtble VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
path = r'C:\Users\username\source'
dir_list = os.listdir(path)
source=""
destination= r"C:\Users\username\destination"
df = pd.DataFrame()
rows = tuple()
If the file already exists, the move function will overwrite it, provided you pass the whole path...including the file name
So add the file name to the destination arg of the shutil.move function...
I have a Db from where I have to display all the columns which match the substring of the column given by user.
The following code works:
c.execute("select *from Transactions where Description like '%sh%' ")
conn.commit()
print(c.fetchall())
conn.close()
But when I try to run this code it returns me an empty list:
def search(col,val):
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("Select *from Transactions where ? Like ? ",(col,'%'+val+'%'))
print(c.fetchall())
search('description',"sh")
Also the result will always be a blank list even if the col name is wrong. as opposed the usual error which says column not found.
Please Help
I have a code that generates a table and prints it as a csv file but when I run it, it also displays certain characters like quotation marks and parenthesis.
I currently don't have pandas, so if there's a solution that does not include it, I would greatly appreciate it. I know it should be something "simple" as all it is, is a formatting issue. Below is the piece of code that prints the table and also my current and desire results
Code:
def PrintAsCsv(table):
for r in table:
print((r[0], r[1], r[3], r[5], r[6], r[7], r[8]))
Current results in the header of the table:
('Ssid' 'Vlan' 'Connected Time' 'Rssi' 'Date' 'Wap Name' 'Device Name')
Desired results in the header of the table:
Ssid Vlan Connected Time Rssi Date Wap Name Device Name
As your fields contain spaces, you'll want to have a different separator, e.g. a comma (default for csv):
def PrintAsCsv(table):
for r in table:
print(','.join((r[0], r[1], r[3], r[5], r[6], r[7], r[8])))
Output:
Ssid,Vlan,Connected Time,Rssi,Date,Wap Name,Device Name
I'm trying to insert the value of the variable test_text into a Postgres 9.6 database, each time the database_insert function is triggered.
I'm using Python 3.6 and psycopg2 v 2.7
If I use the below code without the placeholder: e.g replace %s with 'test' and remove , (test_text) - it works as I would expect...
def database_insert(update):
test_text = 'This is some test text'
with psycopg2.connect("DB CONNECTION DETAILS ARE HERE'") as conn:
cur = conn.cursor()
cur.execute("INSERT INTO test VALUES(%s);", (test_text))
conn.commit()
cur.close()
conn.close()
However when the function trys to insert the value of the test_text variable using the %s placeholder, I get the error below...
cur.execute("INSERT INTO test VALUES(%s);", (test_text))
TypeError: not all arguments converted during string formatting
Any help on where I am going wrong with this will be much appreciated!
There's a subtle issue here.
You need a comma to make a tuple not just the parens/brackets.
So simply change to:
cur.execute("INSERT INTO test VALUES(%s);", (test_text,))
And you should be good!