Python script and mysql database with update query does't work - python

I have a python script that I created to update a MySQL database the insert work perfect but when I tried to update it nothing happen and it doesn't change.
The console displays this error from the try and except
Unable to print data
Can anyone help me to fix this error?
MySQL database
Database student
Table structure for table stu
Column Type Null Default
ID int(8) No
Name varchar(255) No
subject varchar(255) No
Dumping data for table stu
11 jhon python
12 jina hjsdhjsd
13 jaSDJ JHAISDJ
Python script
#!/usr/bin/python
# UPDATE AND delete some values from the database ###
import MySQLdb
db = MySQLdb.Connect("localhost", "****", "******", "student")
cursor = db.cursor()
sql = "UPDATE STU SET NAME = MAROUN, SUBJECT = C++ WHERE ID = 13 "
try:
cursor.execute(sql)
# r = cursor.fetchall()
# for row in r:
# ID = row[0]
# NAME = row[1]
# SUBJECT = row[2]
# print "ID = %d, LAST_NAME = %s, SUBJECT = %s " %(ID, NAME, SUBJECT)
print "update ok "
except Exception as e:
print e
db.close()

Related

Python SQLITE3 update column value based on where condition applied to a table

I have a SQLite table that I wanted to update. This table ('abc') already has a row inserted through some other process for id and useremail. Now, I want my query to lookup this record based on where condition (on useremail) and update the value of column logintime. I am pretty new to Sqlite so need some help in figuring it out. Code below -
creating a new table (works OK)
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS abc (
id INTEGER PRIMARY KEY,
useremail TEXT,
logintime TEXT,
logouttime TEXT
);
""")
conn.commit()
conn.close()
code for inserting a record (works OK)
email = ['jojo#jojo.com']
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
c.execute('insert into abc (useremail) values(?)', email)
code for updating column logintime where value in column useremail = email:
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
now = datetime.now()
c.execute('UPDATE abc SET logintime = ? WHERE useremail = ?', (now, email))
I am having trouble with this c.execute statement.

Updating results from a mysql-connector fetchall

I'm trying to select certain records from the civicrm_address table and update the geocode columns. I use fetchall to retrieve the rows then, within the same loop, I try to update with the results of the geocoder API, passing the civicrm_address.id value in the update_sql statement.
The rowcount after the attempted update and commit is always -1 so I am assuming it failed for some reason but I have yet to figure out why.
import geocoder
import mysql.connector
mydb = mysql.connector.connect(
[redacted]
)
mycursor = mydb.cursor(dictionary=True)
update_cursor = mydb.cursor()
sql = """
select
a.id
, street_address
, city
, abbreviation
from
civicrm_address a
, civicrm_state_province b
where
location_type_id = 6
and
a.state_province_id = b.id
and
street_address is not null
and
city is not null
limit 5
"""
mycursor.execute(sql)
rows = mycursor.fetchall()
print(mycursor.rowcount, "records selected")
for row in rows:
address_id = int(row["id"])
street_address = str(row["street_address"])
city = str(row["city"])
state = str(row["abbreviation"])
myaddress = street_address + " " + city + ", " + state
g = geocoder.arcgis(myaddress)
d = g.json
latitude = d["lat"]
longitude = d["lng"]
update_sql = """
begin work;
update
civicrm_address
set
geo_code_1 = %s
, geo_code_2 = %s
where
id = %s
"""
var=(latitude, longitude, address_id)
print(var)
update_cursor.execute(update_sql, var, multi=True)
mydb.commit()
print(update_cursor.rowcount)
mycursor.close()
update_cursor.close()
mydb.close()
Here is a simpler script:
I have executed the update_sql statement directly in the MySQL workbench and it succeeds. It is not working from Python.
import geocoder
import mysql.connector
try:
mydb = mysql.connector.connect(
[redacted]
)
mycursor = mydb.cursor(dictionary=True)
update_cursor = mydb.cursor()
update_sql = """
begin work;
update
civicrm_address
set
geo_code_1 = 37.3445
, geo_code_2 = -118.5366074
where
id = 65450;
"""
update_cursor.execute(update_sql, multi=True)
mydb.commit()
print(update_cursor.rowcount, "row(s) were updated")
except mysql.connector.Error as error:
print("Failed to update record to database: {}".format(error))
mydb.rollback()
finally:
# closing database connection.
if (mydb.is_connected()):
mydb.close()
I have it working now. I did remove the "begin work" statement but not the multi=True and it wouldn't work. Later I removed the multi=True statement and it works.

python MySQL update specific column fetchall()

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.
for row in cur.fetchall():
if row[3] == 0:
cur.execute("UPDATE tble SET count = 1 WHERE name = %s" %row[1])
Assuming your table has this structure:
CREATE TABLE `test` (
`sno` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`count` int(11) NOT NULL,
`dtCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Here is the simple code code-
import pymysql
conn = pymysql.connect(host='localhost', unix_socket='', user='USER', passwd='PASSWORD', db='DATABASENAME')
cur = conn.cursor()
cur.execute("SELECT * FROM test")
for r in cur:
curr = conn.cursor()
sql = """UPDATE test SET count = 1 WHERE name = '%s'""" % r[1]
# print(sql)
try:
# Execute the SQL command
curr.execute(sql)
# Commit your changes in the database
conn.commit()
except:
# Rollback in case there is any error
conn.rollback()
curr.close()
cur.close()
conn.close()
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.

Unexpected output of weird characters for Python sqlite3 database

My python 3.6 code is supposed to create a database and create a table inside it.
import sqlite3
db_filename = 'database.db'
connect = sqlite3.connect(db_filename)
c = connect.cursor()
c.execute('CREATE TABLE IF NOT EXISTS task (id number PRIMARY KEY, priority integer, details text, status text)')
connect.commit()
connect.close()
However the output is not what I intended. I am getting weird characters included in the .db file;
SQLite format 3  # .�
� b b� k�9tabletasktaskCREATE TABLE task (id number PRIMARY KEY, priority integer, details text, status text)'; indexsqlite_autoindex_task_1task


If anyone could tell me where I went wrong I would be grateful.
Thanks.
There is nothing wrong here. To view a .db file you need db viewer or reader tool. http://sqlitebrowser.org/ has DB browser for SQLite which can be used to view your database. You can install it and use it to read your .db file.
If you want to use the table you can do so by inserting elements in the table and viewing it as follows:
import sqlite3
db_filename = 'database.db'
connect = sqlite3.connect(db_filename)
c = connect.cursor()
c.execute('CREATE TABLE IF NOT EXISTS task (id number PRIMARY KEY, priority integer, details text, status text)')
c.execute("INSERT INTO task (id,priority,details,status) \
VALUES (1,22,'ABC','YES' )");
cursor = c.execute("SELECT id,priority,details,status from task")
for row in cursor:
print ("ID = ", row[0])
print ("PRIORITY = ", row[1])
print ("DETAILS = ", row[2])
print ("STATUS = ", row[3], "\n")
connect.commit()
connect.close()
OUTPUT:
ID = 1
PRIORITY = 22
DETAILS = ABC
STATUS = YES

Failing to fetch data from MySQLdb database

[enter image description here][1]I am currently making a project for school and the time for reaching the wall has come.
I am trying to fetch data from the USB port on Raspberry Pi 3+. I have connected an Arduino Nano and I am sending a string(UID number in decimal of an RFID Card) from it to the Pi via the USB port. Everything works fine here, I can print out the string(ID) without a problem. I am comparing the ID from the card with the one in my database, and if I put a static number ( commented below in the code) it prints the data. However if I try with the serial line, nothing happens. It seems like it doesn't fetch the data at all. The outlook of my database is underneath and the python code as well.
Thanks in Advance !!
card_id serial_no LastName FirstName
1 | 2136106133 | Hansen | Peter |
2 | 117254270 | Larsen | Thompson |
#!/usr/bin/env python
import MySQLdb
import serial
ser = serial.Serial('/dev/ttyUSB0',9600)
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="root", # your password
db="RFID") # name of the data base
cur=db.cursor()
CardID = 0
LastName = ""
FirstName = ""
while True:
CardID=ser.readline()
print "pweasda"
print CardID
print "pewpew"
# CardID = 117254270 - this works. The problem is that I have many RFID cards/tags with different IDs of course. With this statement it prints everything correctly.
cur.execute('SELECT * FROM cards WHERE serial_no=%s',(CardID))
results = cur.fetchall()
for row in results:
FirstName = row[3]
LastName = row [2]
serial_no = row [1]
card_id = row [0]
#print the fetched results
print "FirstName=%s,LastName=%s,serial_no=%s,card_id=%s" % \
(FirstName, LastName, serial_no, card_id )
db.commit()
print "Data committed"
output image (no errors): [1]: http://postimg.org/image/jf2doogrv/
Possible solution could be:
import sqlite3
conn = sqlite3.connect("users.db")#path to your sqlite db file!
cursor = conn.cursor()
CardID=ser.readline().strip()
sql = "SELECT * FROM cards WHERE serial_no=?"
cursor.execute(sql, [(CardID)])
try:
results = cursor.fetchall()[0]# just fetching the first row only, you can loop through all rows here!
FirstName = results[3]
LastName = results[2]
serial_no = results[1]
card_id = results[0]
print "FirstName=%s,LastName=%s,serial_no=%s,card_id=%s" % \
(FirstName, LastName, serial_no, card_id )
except IndexError as e:
print 'CardID Not Exist'+str(e)
except Exception as e2:
print(str(e2))
In above code I am assuming the database is in sqlite DB, and also handled the exceptions so you can figure out the runtime error, if any!

Categories