Python Update in MySQL - python

I've been struggling to get this really simple query to actually work in Python. I am a complete python newb, and strings seem to be handled a lot differently than what I am accustomed to.
The query I am trying...
cur = db.cursor()
cur.execute("SELECT bluetooth_Id FROM student_Data")
data = cur.fetchall()
for row in data :
bluetoothId=row[0]
result=bluetooth.lookup_name(bluetoothId,timeout=5)
print(result)
if(result != None):
cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s",(bluetoothId))
print("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s",(bluetoothId))
What seems to be the problem is that my actual SQL query is not correctly formatted.. I know this because that last print statement returns this
('UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s', 'th:is:is:my:bt:id')
and of course that id is not actually the id it returns... I didn't want to give that to you :)
I am following examples to the dot, and not getting anywhere.. my bluetooth is on, the program sees my bluetooth id, it processes through the list of ids already in my mysql table, but it isn't updating any records.
and I did check to make sure I entered my id in the mysql table correctly, so that is not the problem either!
Update
I was able to get the correct MySQL query created using this:
cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id = '%s"%(bluetoothId)+"'")
which creates
UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id = '11:11:11:11:11:11'
but the MySQL table still isn't updating correctly.. I'll have to look into seeing why that is...

The solution was this:
cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id = '%s"%(bluetoothId)+"'")
and then I had to add
db.commit()
After the execute, in order to actually commit the changes to the MySQL table.
Thanks all for the help:)
Python mySQL Update, Working but not updating table

You need to do this:
cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id= %s"%(bluetoothId))
If you are doing substitution, you need a % instead of a comma

Related

Updating an SQL table while searching another SQL table

I have an SQL database "Garage.db" that has 3 tables:
Customer, Car and MOT
I want to update the field BookedMOT in the MOT table when someone has entered a Registration that is in the Car table. Can someone help me with the SQL query that can do this, thank you.
I am coding this in python 3.6 using tkinter. Here is my attempt,
def Booked(self):
date = Date.get()
month = Month.get()
year = Year.get()
BookedMOT = (date + '/' + month + '/' + year)
Registration = self.RegistrationEnt.get()
with sqlite3.connect('Garage.db') as db:
cursor = db.cursor()
add_date = ('UPDATE MOT SET MOT.BookedMOT = ? FROM Car WHERE Car.Registration = ?')
cursor.execute(add_date,[(BookedMOT), (Registration)])
db.commit()
(this addresses some Python problems I noticed before even realising that the SQL didn't look right, which should probably be fixed first)
Try this:
with sqlite3.connect('Garage.db') as db:
db.execute(add_date, (BookedMOT, Registration))
In general, when you say with ... as x:, you should probably use x inside the with block. After the block finished it did an automatic commit and trying to use db or cursor afterwards is probably incorrect. The with also means that you don't have to db.commit() any more.
sqlite3 connection objects (db in this case) have an execute method:
This is a nonstandard shortcut that creates a cursor object by calling the cursor() method, calls the cursor’s execute() method with the parameters given, and returns the cursor.
Finally, you had some redundant parentheses that could be removed.

SELECT in a while loop in python with mysql

I am trying to find the latest entry in a MySQL database by using a query with SELECT MAX(id). I already get the latest id, so I know the query works, but now I want to use it in a while loop so I keep getting the latest entry with each iteration.
This is what I have so far:
import pymysql
con = pymysql.connect(host='.....', user='.....',
password='.....', database='.....')
cur = con.cursor()
while True:
query = "SELECT MAX(id) FROM reports"
cur.execute(query)
data = cur.fetchall()
last = (data[0][0])
print(last)
The problem is that I keep getting the same result after updating the database. For instance, right now I have 45 entries, so my script prints '45' in a while loop. But after I add another row to the table it keeps printing '45' instead of the '46' I would expect. When I stop the script and run it again, it will print '46' and keep printing this even after I add another row.
I have only started working with MySQL about two weeks ago, so I don't have all that much knowledge about it. I feel like I'm missing something really small here. What should I do? Any help would be greatly appreciated.
I had this same problem, and just wanted to make it clear for anyone else searching for the solution.
Setting autocommit to True solved my issue and didn't require calling a commit after each query.
import pymysql
con = pymysql.connect(host='.....', user='.....',
password='.....', database='.....')
con.autocommit = True
cur = con.cursor()
while True:
query = "SELECT MAX(id) FROM reports"
cur.execute(query)
data = cur.fetchall()
last = (data[0][0])
print(last)
Here is a link to the documentation

SQL query returning None in Python script while there are records in table

I am trying to write a simple Python script that gets data from an API, stores it in a MySQL database, and performs some calculations on that data. I try fetch all data from a table where I just inserted some, but that query keeps returning None.
Part that doesn't work:
import MySQLdb
db = MySQLdb.connect("localhost", "stijn", "password", "GW2")
curs = db.cursor()
curs.execute("select gw2_id, naam from PrijzenMats")
for record in curs.fetchall():
curs2 = db.cursor()
curs2.execute("insert into MaterialPrijzenLogs(mat,prijs,tijd) values(%s, %s, %s)", (record[1], prijs, tijd))
db.commit()
curs2.execute("select prijs from MaterialPrijzenLogs")
top10 = len(curs2.fetchall())/10
print(str(len(curs2.fetchall())))
That last print keeps giving 0, even when I populate the table before running the script.
Full code
I solved the problem. Apparently when you call fetchall() it doesn't just get the data from the cursor like a normal getter in Java would do, but it also deletes the data from the cursor. In my code I called fetchall() first to initialize a variable, and after that I tried to print the length of curs2.fetchall(), which had become 0 at that point. This can be easily solved by adding something like myList = curs2.fetchall() directly after curs2.execute("select prijs from MaterialPrijzenLogs") and using the myList variable in the rest of the code instead of curs2.fetchall(). I did not include the declaration of that top10 variable in the code example in my original question because I thought it had nothing to do with the problem. I edited the question so future readers can easily understand the problem.

Python & SQL. Inserting variable in column while in for loop

as part of my sentiment analysis on tweets, I need extract tweets from my database, run a python script to get the sentiment score and insert it back into the database.
Part of my code:
#conneting to database (works perfect)
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=xxxxxxx\SQLEXPRESS;DATABASE=TestTwitter;UID=;PWD=')
cursor = cnxn.cursor()
#Alter table (works perfect)
cursor.execute("ALTER TABLE TestTable ADD score2 varchar(255);")
#select tweet from each row and calculate score (works perfect)
cursor.execute("SELECT TestTable.Tweet FROM TestTable")
for row in cursor.fetchall():
print (row[0])
sentim = sentiment(row[0])
print (sentim)
#update table and add sentiment score for each row (not so perfect)
cursor.execute("Update TestTable SET score2 = '" + (str(sentim)) + "';")
cnxn.commit()
When updating the table, all rows get the same sentiment value as the first tweet instead of their own. The "print (sentiment)" shows the score of each tweet one by one, but it seems like the loop doesn't work when updating the table. Any way to fix this?
This isn't a problem with the while loop, but with your UPDATE command; you're telling it to update all rows in TestTable, not just the one you're working on. You need to provide a WHERE condition to that UPDATE.
cursor.execute("SELECT TestTable.Tweet, TestTable.id FROM TestTable")
for row in cursor.fetchall():
...
cursor.execute("Update TestTable SET score2 = %s WHERE id = %s;", (sentim, row[1]))
(assuming your primary key column is called id).
Note also that you should get into the habit of using parameterized queries; although there's no chance of SQL injection in this code, because nothing is coming from user input, other code might have that problem so it's best to avoid it altogether.
You need to qualify the update clause with a where clause that limits the rows you update to the one you want to modify.
Something like cursor.execute("Update TestTable SET score2 = '" + (str(sentim)) + "' where Tweet = '" + row[0] + "';")
Instead of using the Tweet column as key you should probably modify your select statement to extract the primary key too and use that in the where clause.
Also, using concatenation to build SQL statements can be a bad idea as it might expose you to SQL injection vulnerabilities so you might want to explore how to use prepared statements or parameters for the query.

Check Python SQL Query result for variable

I'm new to Python and working with SQL queries. I have a database that contains a table with meetings and their date along with an ID. What I want to do is check what meetings are happening on today's date. The code below results in showing all the meeting ID's that are happening on todays date. However I then want to check if a certain meeting ID is in the results, which I have stored as a variable, and if it is in there to carry out an IF function so I can then elaborate.
cur.execute("SELECT id FROM meeting WHERE DATE(starttime) = DATE(NOW())")
for row in cur.fetchall() :
print row[0]
You can ask the database to tell you if the id is there:
cur.execute("SELECT id FROM meeting WHERE DATE(starttime) = DATE(NOW()) AND id=%s", (id,))
if cur.rowcount:
# The id is there
else:
# The id is not there.
I am assuming that you are using MySQLdb here; different database adapters use slightly different query parameter styles. Others might use ? instead of %s.

Categories