I am working on a PyQT5 application with part of it being a table that displays movie ratings in a QTableWidget. When I add a movie to the database, I clear the old table and run a new select query to get the ten most recent movies logged. This query works correctly the first time, but fails every time afterwards. Each time after the first add, the select query just returns the 10 entries from the first time the query was executed instead of returning movies logged since then. What's confusing me is that if I run the query in MySQL workbench, it runs correctly every time. It's only when the entries are passed to my application that things go wrong. Here is the refresh method that is run after an entry is added:
def refreshLastTen(self):
#Refreshes the table of recently watched movies after a new entry is added or a change
print('Refreshing Last10 Table')
self.LastTenTable.clearContents()
#When adding one new movie, the refresh works fine. Anything more than that, the result from the first add is returned every time
sql = "SELECT * FROM log ORDER BY LOG_MOVIE_DATE desc LIMIT 0, 10" #Selects top 10 results from the table
cursor = dbConnection.cursor()
cursor.execute(sql)
myresult = cursor.fetchall()
cursor.close()
for row_number, row_data in enumerate(myresult): #Adds data from select statement to the table
for column_number, data in enumerate(row_data):
self.LastTenTable.setItem(row_number, column_number,QtWidgets.QTableWidgetItem(str(data)))
For example, I add the movie "Test 1" at the current date (theoretically the most recently watched) to the database and the refresh method returns the following:
After this, I add another movie "Test 2" at the current date and instead of returning "Test 2" and "Test 1" as the most recent 2 movies in the list, the same result from the first query is returned again. This continues no matter how many more movies you add. As stated before, if you were to then run the same query in MySQL workbench, it would correctly return "Test 2" and "Test 1" as the two most recent entries. Does anyone have any ideas of what could be happening?
*Edit 1: Here is the code used in my insert method to add a movie to the database:
if self.validateSubmission() == True:
sql = "INSERT INTO log (LOG_MOVIE_TITLE, LOG_MOVIE_DATE, LOG_MOVIE_RATING, LOG_MOVIE_GENRE, LOG_MOVIE_LOCATION, LOG_MOVIE_COMMENTS) VALUES (%s, %s, %s, %s, %s, %s)"
vals = [self.titleVal.text(), self.dateVal.date().toString('yyyy-MM-dd'), self.ratingVal.currentText(), self.genreVal.currentText(), self.locationVal, self.commentVal.toPlainText()]
cursor = dbConnection.cursor()
cursor.execute(sql, vals)
dbConnection.commit()
cursor.close()
dbConnection.close()
*Edit 2: Here is a screenshot from MySQL Workbench showing the select query working:
*Edit 3: Now I am wondering if it has to do with how I am handling the dbConnection. The refreshLastTen method is in the app's main page class whereas the add happens in an add form class. Each class has dbConnection explicitly defined like this:
dbConnection = mysql.connector.connect(
host="localhost",
user="root",
passwd="pwd",
database="moviesheet"
)
I am not sure if this causes a disconnect or collision of some sort. I added the following to close the connection in the add form class after the add is done just in case:
dbConnection.close()
One other oddity that I noticed is that if I run the query in the add form class after the add, it returns the correct result. It seems like it might just be related to the main window class.
I'm trying to use sqlite3 in python to delete a selection of rows from a table. My attempt fails, but I can't work out why.
The sql query works ok, but I can't implement it within the python code.
I have a set of records that are moved from current_table to archive_table after a period of time.
I'd like to clean up the current_table by removing those rows that are in the archive_table (matched on id).
Intended SQL query:
DELETE FROM current_table WHERE id IN ( SELECT id FROM archive_table);
Attempted python code:
import sqlite3
def clean_up(current_table, archive_table):
db = sqlite3.connect(sqlite_db)
cursor = db.cursor()
sql_query_delete = '''DELETE FROM %s WHERE id IN ( SELECT id FROM %s);''' % (current_table, archive_table)
try:
cursor.execute(sql_query_delete)
db.commit()
db.close()
except:
print("error deleting")
Now working. The database file was locked by another process. Removing the pointless try/except led me to the detailed error message.
I have just started using MySQLdb in python. I am able to create table but when I try to insert, no rows are inserted into the table and its shows that table is still empty.
import MySQLdb
db = MySQLdb.connect("localhost","root","shivam","test")
cursor = db.cursor()
s = "DROP TABLE IF EXISTS batting"
cursor.execute(s)
s = """create table batting (
name varchar(50) primary key,
matches integer(5),
innings integer(5),
runs integer(5),
highest integer(3),
strikerate integer(3),
hundreds integer(3),
fifties integer(3)
)"""
cursor.execute(s)
s = """insert into batting(name) values(
"shivam")"""
cursor.execute(s)
db.close()
Where I could be going wrong?
You forgot to commit your connection. Simply add:
cursor.execute(s)
db.commit()
Have a look at this. It explains why you need to commit
am trying to insert the data entered into the web form into database table,i am passing the data to the function to insert the data,but it was not successful below is my code
def addnew_to_database(tid,pid,usid,address,status,phno,email,ord_date,del_date):
connection = mysql.connector.connect(user='admin_operations', password='mypassword',host='127.0.0.1',database='tracking_system')
try:
print tid,pid,usid,address,status,phno,email,ord_date,del_date
cursor = connection.cursor()
cursor.execute("insert into track_table (tid,pid,usid,address,status,phno,email,ord_date,del_date) values(tid,pid,usid,address,status,phno,email,ord_date,del_date)")
cursor.execute("insert into user_table (tid,usid) values(tid,usid)")
finally:
connection.commit()
connection.close()
You should pass the variables as an argument to .execute instead of putting them in the actual query. E.g.:
cursor.execute("""insert into track_table
(tid,pid,usid,address,status,phno,email,ord_date,del_date)
values (%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
(tid,pid,usid,address,status,phno,email,ord_date,del_date))
cursor.execute("""insert into user_table
(tid,usid)
values (%s,%s)""",(tid,usid))
You should tell us what API you are using and what the error code is.
You should define the values within the execution, right now within the sql statement as a string they are not referencing anything.
Typically when you use a variable name inside of a sql statement this way, you need to indicate that it is a variable you are binding data to. This might be replacing it with (1,2,3,4..) or (%s,%s,...) that corresponds to an ordered list or using variable names (:tid,:pid,...) that you then define the values of with a dictionary as the second argument of execute().
Like this:
track_table_data = [tid,pid,usid,address,status,phno,email,ord_date,del_date]
user_table_data = [tid,usid]
cursor.execute("insert into track_table (tid,pid,usid,address,status,phno,email,ord_date,del_date) values(1,2,3,4,5,6,7,8,9)", track_table_data)
cursor.execute("insert into user_table (tid,usid) values(1,2)",user_table_data)
or
cursor.execute("insert into track_table (tid,pid,usid,address,status,phno,email,ord_date,del_date) values(:tid,:pid,:usid,:address,:status,:phno,:email,:ord_date,:del_date))", {'tid':tid,'pid':pid,'usid':usid,'address':address,'status':status,'phno':status,'email':email,'ord_date':ord_date,'del_date':del_date})
cursor.execute("insert into user_table (tid,usid) values(:tid,:usid)",{'tid':tid,'usid':usid})
I am trying to write into my localhost MySQL database.
I have created a database named "test", a table called "price_update" and a row called "model"
When I run the script below I get no errors, however, I also get nothing written to my database.
I am not sure where to start looking for the problem. the row is varchar(10) and collation utf9_general_ci.
import MySQLdb
conn = MySQLdb.connect(host="127.0.0.1",user="someUser",passwd="somePassword",db="test")
query = "INSERT INTO price_update (model) values ('12345')"
x = conn.cursor()
x.execute(query)
row = x.fetchall()
You have to commit the changes:
conn.commit()
Also, I'd make your query safer:
query = "INSERT INTO price_update (model) values (%s)"
...
x.execute(query, ('12345',))