mysql sum only producing 1 - python

I've looking around for a solution but can't seem to spot what I' doing wrong. I have a mysql database with a table with 2 columns: clock (contains a timestamp), and state (either contains 1 or 0). When a button is pressed on my breadboard (I am using a raspberry pi), 1 is entered into the database which updates continually, and if the button is not being pressed, 0 is entered into the table. This works as I have selecting the table in command line and the appropriate number of 1's and 0's are displayed.
In a seperate python file, the database and table are called and supposedly a sum of the state column is taken, and if this is 1 or more, I know the button has been pressed in the last 30 seconds as the table will clear every 30 seconds.
The issue is that however many 1's and 0's, and even when the table is empty, the sum only returns 1. I am very new to python so this error could be embarrisingly small, thanks for your help all the same!
Here is the entire python file for the sum:
import MySQLdb
conn = MySQLDB.connect('localhost', 'root', 'password', 'sensordb')
cur = conn.cursor()
but1 = cur.execute("SELECT SUM(state) FROM button1")
print "%d" % but1

You need to fetch the row as well.
cur.execute("SELECT SUM(state) FROM button1")
row = cur.fetchone()
while row is not None:
print(row)
row = cur.fetchone()

You are nearly there....
After the cur.execute(....)
You then need to read the output...
for result in cursor.execute("Your QUERY"):
if result.with_rows:
print("Rows produced by statement '{}':".format(
result.statement))
print(result.fetchall())
Hope this helps you....

Related

The tkinter combobox does not work well with sqlite3 database

This is the simple code I want to execute. I want the elements of tkinter combobox come from sqlite3 database it does the job but It appends the first row and first column values many times(no of rows in database) . I want it to append the first column of each rows of databse.
con_caster = sqlite3.connect('caster.db')
con_sec = sqlite3.connect('section.db')
cur_caster = con_caster.cursor()
con_sec = con_sec.cursor()
#cur_caster.execute("DROP TABLE IF EXISTS autos;") # use this line only if you want to overwrite existing table
cur_caster.execute("CREATE TABLE IF NOT EXISTS caster ('casterid' TEXT, 'casterradius' NUMBER);")
cur_caster = con_caster.cursor()
query = cur_caster.execute('SELECT casterid FROM caster')
caster_data = []
for row in cur_caster.fetchall():
caster_data.append(row[0])
combo['values'] = caster_data
con_caster.commit()
And this is how I have created the rows in database
def add_to_database():
i=0
# add details to database
caster_data.append((add_cid.get()))
cur_caster.execute("INSERT INTO caster VALUES (?, ?);", (caster_data[i],caster_data[i] ))
con_caster.commit()
combo['values'] = caster_data
i+=1
When I delete the database file and run the app it shows
When I add data, the combobox looks like
After closing and opening app again he combobox looks like
And the database also changes same as tyhe combobox.
Looking for the help in this.
Thank you so much in advance
I finally removed the bug, There was problem with the data addition method.
Every time I needed to add data ro database I used to add the first element instead of entry value which was caster_data[i]
The correct snippet is.
def add_to_database():
i=0
caster_data.append((add_cid.get()))
cur_caster.execute("INSERT INTO caster VALUES (?, ?);", (add_cid.get(),add_cr.get() ))
con_caster.commit()
combo['values'] = caster_data
i+=1

can I get only the updated data from database instead of all the data

I am using sqlite3 in python 3 I want to get only the updated data from the database. what I mean by that can be explained as follows: the database already has 2 rows of data and I add 2 more rows of data. How can I read only the updated rows instead of total rows
Note: indexing may not help here because the no of rows updating will change.
def read_all():
cur = con.cursor()
cur.execute("SELECT * FROM CVT")
rows = cur.fetchall()
# print(rows[-1])
assert cur.rowcount == len(rows)
lastrowids = range(cur.lastrowid - cur.rowcount + 1, cur.lastrowid + 1)
print(lastrowids)
If you insert rows "one by one" like that
cursor.execute('INSERT INTO foo (xxxx) VALUES (xxxx)')
You then can retrieve the last inserted rows id :
last_inserted_id = cursor.lastrowid
BUT it will work ONLY if you insert a single row with execute. It will return None if you try to use it after a executemany.
If you are trying to get multiple ids of rows that were inserted at the same time see that answer that may help you.

Update a PostgreSql table using a Python variable

I have the following table in my PostgreSql database with 1 row of data.
I want to update the value in the "diagnosis" column (currently 3) to another number. My python code is below:
Based on my code below, the "diagnosis" column should equal whatever number is assigned to the python diagnosis variable. In this case, the "diagnosis" column in my table should equal 5.
diagnosis = 5;
# eyeball
conn = psycopg2.connect("dbname=eyeballdbfinal user=postgres")
print ("Database opened successfully")
cur = conn.cursor()
cur.execute("UPDATE eyeballtables set DIAGNOSIS = diagnosis where id = 1") # fix this
conn.commit()
print("Total updated rows:", cur.rowcount)
But my SQL code inside my python is not working. Specifically, after running my python code above, my table should have 5 as the diagnosis. Instead, nothing changes. I think this part of the code DIAGNOSIS = diagnosis is not working.
What am I doing wrong?
Use the variable as a parameter:
cur.execute("UPDATE eyeballtables set DIAGNOSIS = %s where id = 1", (diagnosis,))
Read: Passing parameters to SQL queries

INSERT within Loop isn't working as I would expect (Python 2.7)

I am running a sentiment analysis against a table with 3 records (Fig 1). My code (Fig 2) seems to work fine when I print the results to screen (Fig 3). For each of the 3 rows I return 3 values - a row ID, sentiment score and magnitude score . (9 results):
However, when I attempt to INSERT the same 9 values into a table (Fig 4) only the 3 values(from the first row) are inserted into my table.
I feel like this is really obvious, but I am perplexed as to what the issue is. Can anyone point out what is preventing the Insert working for all 3 iterations of the loop.
New to Coding.
Fig 1.
Fig 2.
import mysql.connector
from google.cloud import language
cnx = mysql.connector.connect(user='Blah', password='Blah',
host='Blah',
database='Blah')
cursor = cnx.cursor(buffered=True)
Latest = ("SELECT ResID, TextResp FROM Response")
client = language.Client()
cursor.execute(Latest)
for row in cursor:
document = client.document_from_text(row[1])
sent_analysis = document.analyze_sentiment()
sentiment = sent_analysis.sentiment
annotations = document.annotate_text(include_sentiment=True, include_syntax=True, include_entities=True)
ResID_ =row[0]
PhraseSent_ = sentiment.score
PhraseMag_ = sentiment.magnitude
print(ResID_)
print(PhraseSent_)
print(PhraseMag_)
cnx.commit()
cursor.close()
cnx.close()
Fig 3.
Fig 4. Loop with INSERT statement that isn't working as expected
Issue was that the cursor that was being iterated through was only holding the first row from the table as opposed to all 3 rows. Changing
for row in cursor:
to
for row in cursor.fetchall():
resolved the issue

How to stream/print the several last appended data from a table in SQL Server using python?

I have a table in my SQL Server that is being updated every minute.
Currently, I get the data from my table using this lines of code:
conn = pymssql.connect(server, user, password, "tempdb")
def print_table():
cursor = conn.cursor(as_dict=True)
cursor.execute('SELECT * FROM EmotionDisturbances WHERE name=%s', 'John Doe')
for row in cursor:
#Show the data:
print("rate=%d, emotion=%s" % (row['rate'], row['emotion']))
conn.close()
In my application, I run this the function every 10 seconds.
How do I update the function so that I only print the last appended data from my table?
Thanks
Assuming you have an auto-incrementing index in column id you'd do:
SELECT * FROM EmotionDisturbances WHERE name = % ORDER BY id DESC LIMIT 1
EDIT: If you want all data that was added after a certain time, then you'll need to migrate your schema to have a created date column if it doesn't have one already, then you can do:
SELECT *
FROM EmotionDisturbances
WHERE name = % AND created >= DATEADD(second, -10, GETDATE())
This would get all of the records created over the last 10 seconds, since you said this function runs every 10 seconds.

Categories

Resources