I have a python script that read data from a MySQL db. There a table called ORARI and basically 3 fields: ID, acceso,spento. I need to read acceso, spento every 10 seconds. ACCESO and SPENTO are edited via a web interface, so they may vary. The problem is that when I run my script i can see the exact data from the db, but when I make a change to these values, the python script show me the initial value, not the updated value.
while True:
time.sleep(10)
dateString = strftime('%H:%M:%S')
orario = ("SELECT * FROM orari WHERE attivo = 1")
cur.execute(orario)
row = cur.fetchone()
acceso = row[1]
spento = row[2]
print acceso
print dateString
print spento
need to insert, after the query: db.commit()
Related
When I run the below code, it continues to return the same information even if I change the data saved in the database or insert another row into the database. When I restart the script it pulls the new updated information. I would like the program to pull the most up to date data.
Any help would be greatly appreciated
def readLastTemp():
cur = db.cursor()
sql = "SELECT Temperature FROM Temperatures ORDER BY ID DESC LIMIT 1"
cur.execute(sql)
results = cur.fetchall()
cur.close()
for row in results:
Temperature = row[0]
return Temperature
while True:
print(readLastTemp())
time.sleep(1)
I have my python script which reads an excel column row by row and returns all rows str(values).
I want to write another script which will allow put these values to sql db. I've already written connect method:
def db_connect():
adr = 'some_addr'
uid = 'some_uid'
pwd = 'pwd'
port = port
dsn_tns = cx_Oracle.makedsn(adr, port, SID)
db = cx_Oracle.connect('username', 'pass', dsn_tns)
cur = db.cursor()
cur.execute('update TABLE set ROW = 666 where ANOTHER_ROW is null')
db.commit()
This method does an update but it sets 666 for ALL rows. How to do it by kind of iteration in sql? For example, first row of output == 1, second == 23, third == 888.
If I understand correctly what you are trying to do here it should be done in two phases. First select all rows for update (based on chosen condition), then you can iteratively update each of these rows.
It cannot be done in single query (or on only single condition that does not change through a number of queries), because SQL works on sets, that's why each time your query is executed you are updating whole table, and in the end only getting result of the last query.
You can use the "rownum" expression, as in:
cur.execute("update TABLE set ROW = rownum where ANOTHER_ROW is null")
This will start with the value 1 and increment up by one for each row updated.
If you want more control over the value to set, you can also do the following in PL/SQL (untested):
cur.execute("""
declare
t_NewValue number;
cursor c_Data is
select ROW, ANOTHER_ROW
from TABLE
where ANOTHER_ROW is null
for update;
begin
t_NewValue := 1;
for row in c_Data loop
update TABLE set ROW = t_NewValue
where current of c_Data;
t_NewValue := t_NewValue + 1;
end loop;
end;""")
This gives you the most control. You can use whatever logic you require to control what the new value should be.
Please take a look at another method which is writing to excel:
adr = 'some_addr'
uid = 'some_uid'
pwd = 'pwd'
port = port
dsn_tns = cx_Oracle.makedsn(adr, port, SID)
db = cx_Oracle.connect('username', 'pass', dsn_tns)
cur = db.cursor()
cells = excel.read_from_cell()
indices_and_statuses = []
stat = execute_script(some_js)
for req_id in cells:
indices_and_statuses.append((cells.index(req_id), stat))
cur.execute("""update TABLE set ROW ="""+"'"+req_id+"'"+"""where ANOTHER_ROW is null""")
db.commit()
db.close()
And in this code when you put print(req_id) in this FOR statement, you will see that req_id is changing. But in DB only the last req_id is saved.
I scripted in Python SQL calls to my MonetDB server (which I verify is running, of course). When I print the calls instead of calling them, the commands look OK, but if I run the original script, it does not crash, it does use the CPU and memory, but nothing is changed in the database, not even the first line is executed. Why?
The Python script looks like this:
# script to merge tables in MonetDB
import re
from monetdb import mapi
server = mapi.Server()
server.connect(hostname="localhost", port=50000, username="monetdb", password="monetdb", database="dbfarm", language="sql")
def tablemerge(stub,yearlist):
for year in yearlist:
# server.cmd('ALTER TABLE %s_%d ADD COLUMN "year" INTEGER DEFAULT %d;' % (stub,year,year))
print 'ALTER TABLE %s_%d ADD COLUMN "year" INTEGER DEFAULT %d;' % (stub,year,year)
newstub = re.sub(r'sys.ds_chocker_lev_', r'', stub)
if year == yearlist[0]:
unioncall = 'CREATE TABLE %s AS SELECT * FROM %s_%d ' % (newstub,stub,year)
else:
unioncall += 'UNION ALL SELECT * FROM %s_%d ' % (stub,year)
unioncall += ';'
server.cmd(unioncall)
# print unioncall
for year in yearlist:
server.cmd('DROP TABLE %s_%d;' % (stub,year))
# print 'DROP TABLE %s_%d;' % (stub,year)
print '%s done.' % stub
for stub in ['civandr']:
tablemerge('sys.ds_chocker_lev_%s' % stub,xrange(1998,2013))
E.g. the first call would be:
ALTER TABLE sys.ds_chocker_lev_civandr_1998 ADD COLUMN "year" INTEGER DEFAULT 1998;
But not even this happens. There is no year column in the table.
Or could I run the script in the console with more output than what I print myself?
Do commit! By default, the autocommit parameter is set to False. You can either do:
server.connect(hostname="localhost", port=50000, username="monetdb", password="monetdb", database="dbfarm", language="sql", autocommit=True)
or simply run:
connection.commit()
connection = monetdb.sql.connect(username=username,password=password,hostname=hostname,port=port,database=database)
cursor = connection.cursor()
cursor.execute('create table test (id int, name varchar(50));')
connection.commit()
I'm fairly new to Python. Here's a script I have that gathers info from our MySQL server hosting our Helpdesk tickets, and will pop up a message box (using EasyGUI's "msgbox()" function) whenever a new ticket arrives.
The issue is that I want my program to continue processing after the popup, regardless of whether the user clicks "OK" or not, even if that means message boxes could keep popping up over each other and must be dismissed one by one; that would be fine with me.
I looked into threading, and either it doesn't work or I did something wrong and need a good guide. Here's my code:
import MySQLdb
import time
from easygui import *
# Connect
db = MySQLdb.connect(host="MySQL.MyDomain.com", user="user", passwd="pass", db="db")
cursor = db.cursor()
# Before-and-after arrays to compare; A change means a new ticket arrived
IDarray = ([0,0,0])
IDarray_prev = ([0,0,0])
# Compare the latest 3 tickets since more than 1 may arrive in my time interval
cursor.execute("SELECT id FROM Tickets ORDER BY id DESC limit 3;")
numrows = int(cursor.rowcount)
for x in range(0,numrows):
row = cursor.fetchone()
for num in row:
IDarray_prev[x] = int(num)
cursor.close()
db.commit()
while 1:
cursor = db.cursor()
cursor.execute("SELECT id FROM Tickets ORDER BY id DESC limit 3;")
numrows = int(cursor.rowcount)
for x in range(0,numrows):
row = cursor.fetchone()
for num in row:
IDarray[x] = int(num)
if(IDarray != IDarray_prev):
cursor.execute("SELECT Subject FROM Tickets ORDER BY id DESC limit 1;")
subject = cursor.fetchone()
for line in subject:
# -----------------------------------------
# STACKOVERFLOW, HERE IS THE MSGBOX LINE!!!
# -----------------------------------------
msgbox("A new ticket has arrived:\n"+line)
# My time interval -- Checks the database every 8 seconds:
time.sleep(8)
IDarray_prev = IDarray[:]
cursor.close()
db.commit()
You can use Python GTK+
It offers non-modal using
set_modal(False)
Hi everyone in php when you fetch data from a mysql database and echo it out you get just whats in the selected row . Say i have a database named workers and a table called names
and names have 5 names in it mic,joe,ashley,lee,and jean. Using SELECT names from names where name = 'jean' and then echoed out the name php would print out jean but in python it would print out ('jean',) how can i fix this so that i can compare the names entered by the user with the names in the database.
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost","root","fgnfgnfgnfgn","workers" )
cursor = db.cursor()
cursor.execute("SELECT names from names where name = 'jean'")
while True:
record = data = cursor.fetchone()
if not record: break
print record
if data == "jean":
print "its like php"
elif data != "jean":
print "its not like php"
db.close()
fetchone() and fetch_row() return objects of type called tuple.
You can use indexes to access elements of tuples, print data[0]
if data[0] == "jean"