I’m new to python and I want to update every record that has count 0 in the database. I have tried a lot can’t find anything like help.
JavaScript
x
4
1
for row in cur.fetchall():
2
if row[3] == 0:
3
cur.execute("UPDATE tble SET count = 1 WHERE name = %s" %row[1])
4
Advertisement
Answer
Assuming your table has this structure:
JavaScript
1
7
1
CREATE TABLE `test` (
2
`sno` int(11) NOT NULL,
3
`name` varchar(50) NOT NULL,
4
`count` int(11) NOT NULL,
5
`dtCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
6
);
7
Here is the simple code code-
JavaScript
1
21
21
1
import pymysql
2
conn = pymysql.connect(host='localhost', unix_socket='', user='USER', passwd='PASSWORD', db='DATABASENAME')
3
cur = conn.cursor()
4
cur.execute("SELECT * FROM test")
5
for r in cur:
6
curr = conn.cursor()
7
sql = """UPDATE test SET count = 1 WHERE name = '%s'""" % r[1]
8
# print(sql)
9
try:
10
# Execute the SQL command
11
curr.execute(sql)
12
# Commit your changes in the database
13
conn.commit()
14
except:
15
# Rollback in case there is any error
16
conn.rollback()
17
curr.close()
18
19
cur.close()
20
conn.close()
21
Also, since you mentioned that you are new to python remember to commit, every time, whenever you run INSERT, UPDATE or DELETE like queries.
Hope it helps.