Python/MySQLdb troubles on Raspberry Pi - python

I'm running into some trouble running python/mysqldb on my raspberry pi. This is a pretty simple script, so I'm not sure what I'm missing. The "SELECT * FROM..." runs with no problem, but I can't seem to update the table with new values. The script runs without throwing errors, but when I ctrl-C, it gives me this:
Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in bound method DictCursor.__del of MySQLdb.cursors.DictCursor object at 0x19dfd90
Here's my script:
dhost = "localhost"
duser = "root"
dname = "rpi"
dpass = "datPassword"
import MySQLdb
try:
con = MySQLdb.connect(dhost,duser,dpass,dname);
cur = con.cursor(MySQLdb.cursors.DictCursor)
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
def websiteToSensor():
cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
rows = cur.fetchall()
for row in rows:
cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
return
while True:
websiteToSensor()
Does anyone have an idea as to why my table isn't updating? Thanks!
***EDIT: SOLUTION***
Thanks to Martijn Pieters, here's my new websiteToSensor() code:
def websiteToSensor():
cur = con.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
rows = cur.fetchall()
num = int(cur.rowcount)
if num > 0:
for row in rows:
cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
con.commit()
cur.close()
con.commit()
else:
cur.close()
con.commit()
return

Try committing your changes:
def websiteToSensor():
cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
rows = cur.fetchall()
for row in rows:
cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
con.commit()
return

Related

python psycopg2 can't load the table in the database

I successfully access the database, however, I can't load the table inside the database. I am quite sure that the name of the table is correct, the database is a mimic iii database. Please give me a helping hand, thanks a lot!
import psycopg2
try:
connection = psycopg2.connect(user="postgres",
password="xxxxxxx",
host="localhost",
port="5432",
database="mimic")
cursor = connection.cursor()
postgreSQL_select_Query = "select * from admissions"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from mobile table using cursor.fetchall")
admissions_records = cursor.fetchall()
print("Print each row and it's columns values")
for row in admissions_records:
print("x = ", row[0], )
print("y = ", row[1])
print("z = ", row[2], "\n")
except (Exception, psycopg2.Error) as error:
print("Error while fetching data from PostgreSQL", error)
finally:
# closing database connection.
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
Here's the output:
Error while fetching data from PostgreSQL relation "admissions" does not exist
LINE 1: select * from admissions
^
PostgreSQL connection is closed

syntax error in mariaDB that i cannot find

i am writing a code to write my gps variables in my database but i get this error everytime i run it:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Long, Status) VALUES (1, 50.821139333333335, 3.2815086666666664, 'Eind')' at line 1
the database has an id that is auto incremented and then the following values i'm trying to add, no clue what's going wrong. maybe you guys have an idea
database.py:
#staticmethod
def execute_sql(sqlQuery, params=None):
result = None
db, cursor = Database.__open_connection()
try:
cursor.execute(sqlQuery, params)
db.commit()
result = cursor.lastrowid
except connector.Error as error:
db.rollback()
result = None
print(f"Error: Data not stored.{error.msg}")
finally:
cursor.close()
db.close()
return result
datarepository.py:
#staticmethod
def create_gps(RouteID, Lat, Long, Status):
sql = "INSERT INTO gps (RouteID, Lat, Long, Status) VALUES (%s, %s, %s, %s)"
params = [RouteID, Lat, Long, Status]
return Database.execute_sql(sql, params)
app.py:
#socketio.on('F2B_GPS')
def gps_aan(toggle, status):
while(toggle != 1):
port = "/dev/serial0"
ser = serial.Serial(port, baudrate=9600, timeout=0.5)
dataout = pynmea2.NMEAStreamReader()
newdata = ser.readline()
if sys.version_info[0] == 3:
newdata = newdata.decode("utf-8", "ignore")
if newdata[0:6] == "$GPRMC":
newmsg = pynmea2.parse(newdata)
lat = newmsg.latitude
lng = newmsg.longitude
gps = "Latitude=" + str(lat) + "and Longitude=" + str(lng)
print(gps)
DataRepository.create_gps(1,lat,lng, status)
print("added")
toggle = 1
Thanks to anyone replying :)
ok i found it you cant use Long since that screws it up in mysql so i had to change it to longitude

I don't know why curs.execute not working

i'm studying about mysql connection with python(pycharm)
i have question about curs.execute()
when it work and when it not work...
in my code i write remarks about not working point
import pymysql
try:
conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')
conn.set_charset('utf8')
curs = conn.cursor(pymysql.cursors.DictCursor) #Dictionary cursor 생성
# curs = conn.cursor()
print("Connected to MySQL")
sql = "SELECT sno, midterm, final from db_score where midterm >= 20 and final >= 20 order by sno"
# sql = "select* from db_score"
curs.execute(sql)
#this point not work :(
except Exception as e:
print(str(e))
finally:
if conn:
curs.close()
conn.close()
print("MySql connection is closed")
and fetchall() didnt work :(\
import pandas as pd
import pymysql
xl_file = 'db_score.xlsx'
df = pd.read_excel(xl_file)
tp = list(df.itertuples(index=False, name=None))
# ('sno', 'attendance', 'homework', 'discussion', 'midterm', 'final', 'score', 'grade')
try:
conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')
conn.set_charset('utf8')
#curs = conn.cursor(pymysql.cursors.DictCursor)
curs = conn.cursor()
print("Connected to MySQL")
sql = "INSERT INTO db_score VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
for i in range(0, len(df.index)):
# print('hi')
curs.execute(sql, tp[i])
#why work i dont know because other part is not working
# sql2 = "SELECT* from db_score"
# curs.execute(sql2)
# try execute, but not work
records = curs.fetchall()
for row in records:
print("why didn't work")
print(row)
#print not work :(
conn.commit()
except Exception as e:
print(str(e))
conn.rollback()
finally:
if conn:
curs.close()
conn.close()
print("MySql connection is closed")
please comment why work and why not work please...
thanks for watching
db connection is so hard:(

why delete in SQL query in PYTHON doesn't commit changes in database?

DELETE FROM ... doesn't work. The right parameters are passed to the function. No errors are returned.
I've tried to modify routing, passing parameters by POST and GET, and I've cried a lot in a fetal position.
conn = mysql.connect()
cursor = mysql.connect().cursor()
cursor.execute("SELECT * FROM food_on_the_table WHERE table_id = %s", table_id)
food_on_the_table = cursor.fetchall()
records = cursor.fetchall()
cursor.execute("DELETE FROM food_on_the_table WHERE row_id = %s", row_id)
conn.commit()
result = cursor.rowcount
message = "rows affected " + str(result)
cursor.close()
No row is deleted from the database. row_i is right, rows affected = 1 as expected.
Try this,
try:
conn = mysql.connect()
with conn.cursor() as cursor:
cursor.execute("SELECT * FROM food_on_the_table WHERE table_id = %s", table_id)
food_on_the_table = cursor.fetchall()
records = food_on_the_table
with conn.cursor() as cursor:
cursor.execute("DELETE FROM food_on_the_table WHERE row_id = %s", row_id)
conn.commit()
finally:
conn.close()

PyMySQL not Inserting Data

I have a piece of code which is taking Windows logs and inserting various pieces of information into an mySQL database. The code is running perfectly with no errors, but does not actually input the data into the table. The table remains blank. I pulled my mySQL syntax from an example with some modification, so I'm not entirely sure what is going wrong. I have a feeling it has either to do with the data types, or some changes I made to the syntax.
import sys
import pymysql
import pymysql.cursors
import win32evtlog # requires pywin32 pre-installed
import win32evtlogutil
import time
server = 'localhost' # name of the target computer to get event logs
logtype = 'System' # 'Application' # 'Security'
hand = win32evtlog.OpenEventLog(server,logtype)
flags =
win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
events = win32evtlog.ReadEventLog(hand, flags,0)
while True:
for event in events:
evt_tp = event.EventType
if evt_tp != (1 or 2 or 8):
eve_cat = str(('Event Category:', event.EventCategory))
eve_timegen = str(('Time Generated:', event.TimeGenerated))
eve_srcnm = str(('Source Name:', event.SourceName))
eve_id = str(('Event ID:', event.EventID))
eve_typ = str(('Event Type:', event.EventType))
data = event.StringInserts
if data:
print ('Event Data:')
for msg in data:
print(msg)
print(type(eve_cat))
print(type(eve_timegen))
print(type(eve_srcnm))
print(type(eve_id))
print(type(eve_typ))
print(type(data))
time.sleep(10)
else:
eve_cat = ('Event Category:', event.EventCategory)
eve_timegen = ('Time Generated:', event.TimeGenerated)
eve_srcnm = ('Source Name:', event.SourceName)
eve_id = ('Event ID:', event.EventID)
eve_typ = ('Event Type:', event.EventType)
data = event.StringInserts
print('There were no errors found')
print(eve_cat)
print(eve_timegen)
print(eve_srcnm)
print(eve_id)
print(eve_typ)
print(data)
time.sleep(10)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='ptest',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `win_logs` (`Category`, `TimeGenerated`, 'SourceName',
'EventID', 'Type') VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, (eve_cat, eve_timegen, eve_srcnm, eve_id, eve_typ))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `Type` FROM `win_logs` WHERE `Category`=%s"
cursor.execute(sql, ('webmaster#python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
I can be very wrong.
But this is python.
Indentation matter.
Try just:
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `win_logs` (`Category`, `TimeGenerated`, 'SourceName`, 'EventID', 'Type') VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, (eve_cat, eve_timegen, eve_srcnm, eve_id, eve_typ))
I guess your cursor is out of with scope

Categories

Resources