UPDATE each row of MySQL with different value in Python - python

To sum it up. I have data in a row of a db (MySQL). This data are used in the script to calculate a value. A for loop is used to calculate this value for each row in the table.
The Problem: The results stored in the variable meant have to be updated in a different column of the same row.
I tried to include the update command in the for loop but I get an error (see below). If I do not include the update-command in the for loop I just get the result of the last row but for all rows!
The script:
for row in rows:
for col in row:
x = map(str.strip,col.lower().split())
st = map(lambda wo: abo.get(wo, 0), x)
meant = numpy.meant(st)
cur.execute("""UPDATE table_x SET result = %s Where text = %s""",(meant, rows))
Unfortunately I am getting this error:
Programming Error: (1064, 'You have an error in your SQL syntax; check the manual...
How can I update the column with each calculated value (meant) of that row?

As I see rows is a list ( or an iterable )
and in your query, you are binding the placeholder with rows ( instead of row? )
cur.execute("""UPDATE table_x SET result = %s Where text = %s""",(meant, rows)
That would most probably create a syntax error.

Related

How to get an individual row in Big Query?

I want to get an individual row from the QueryJob in BQ. My query: select count(*) from ... returns a single row & I want to read the count value which is its first column. So if I can get the first row then I can do row[0] for the first column. I can iterate: row in queryJob but since I require only the first row this seems unneccesary.
Below is what I've tried:
row = self.client.query(count_query)
count = row.result()[0]
This gives an error:
'QueryJob' object is not subscriptable"
How can I get individual rows from queryJob by the row index?
Just do:
row = self.client.query(count_query)
result = row.result().total_rows
This will give the count from the query
you can use to_dataframe():
result = self.client.query(count_query).to_dataframe()
#if you want to result as a integer:
result = self.client.query(count_query).to_dataframe()['first_column_name'].iat[0]

If statement in Flask using string variable from SQL database

I'm creating a program where I need to check if a certain cell in a table equals a string value and, if it does not, to not change that value. Here is some snippet of the code for clarification:
if (db.execute("SELECT :rowchosen FROM userboard WHERE column=:columnchosen", rowchosen = rowchosen, columnchosen = columnchosen)) == '-'):
#change value of cell
else:
#go to a new page that displays an error
Yet, whenever I run this code, I always get an error because the value (I believe) prints as a dictionary value, something like {"row" = 'row'} of that sort. Any help/advice as to why this happens?
Are you sure that userboard is the database and not the table?
i think, here is what you want to do
conn = sqlite3.connect(db_file)
cur = conn.cursor()
cur.execute("SELECT * FROM userboard WHERE one=?", (columnchosen,))
rows = cur.fetchall()
for row in rows:
print(row)
now, in the loop for row in rows: you need to perform your check. For all the rows returned, you need to check each row for - in the appropriate column
also check out http://www.sqlitetutorial.net/sqlite-python/sqlite-python-select/

Why is `for...in` returning a tuple when trying to iterate through rows returned by query?

I select 1 column from a table in a database. I want to iterate through each of the results. Why is it when I do this it’s a tuple instead of a single value?
con = psycopg2.connect(…)
cur = con.cursor()
stmt = "SELECT DISTINCT inventory_pkg FROM {}.{} WHERE inventory_pkg IS NOT NULL;".format(schema, tableName)
cur.execute(stmt)
con.commit()
referenced = cur.fetchall()
for destTbl in referenced:#why is destTbl a single element tuple?
print('destTbl: '+str(referenced))
stmt = "SELECT attr_name, attr_rule FROM {}.{} WHERE ppm_table_name = {};".format(schema, tableName, destTbl)#this fails because the where clause gets messed up because ‘destTbl’ has a comma after it
cur.execute(stmt)
Because that's what the db api does: always returns a tuple for each row in the result.
It's pretty simple to refer to destTbl[0] wherever you need to.
Because you are getting rows from your database, and the API is being consistent.
If your query asked for * columns, or a specific number of columns that is greater than 1, you'd also need a tuple or list to hold those columns for each row.
In other words, just because you only have one column in this query doesn't mean the API suddenly will change what kind of object it returns to model a row.
Simply always treat a row as a sequence and use indexing or tuple assignment to get a specific value out. Use:
inventory_pkg = destTbl[0]
or
inventory_pkg, = destTbl
for example.

How to modify a column present in a mysql database through python?

I'm able to connect with my database. But I want to change the values present in that particular column.
cursor.execute("SELECT * FROM foo;")
rows = cursor.fetchall()
for row in rows:
print(row)
Output of the above code is,
('foo,bar,foo,bar',)
('foobar,bar',)
('foo,bar,buz,buz',)
I'm able to replace the value by,
rows = cursor.fetchall()
for row in rows:
print(re.sub(r'^[^,]*,', '', row[0]))
cursor.close()
returns,
bar,foo,bar
bar
bar,buz,buz
but I don't know how to setback the altered string to that particular column.
I think i need to use update query, so I tried
for row in rows:
cursor.execute("UPDATE foo SET categories=%s;", re.sub(r'^[^,]*,', '', row[0]))
But it returns an error message of,
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1
As i said in comment you need to specify the column ID for your query :
for row in rows:
sub=re.sub(r'^[^,]*,', '', row[0])
cursor.execute("UPDATE drug_specifications SET categories=%s where id=%s;",(sub, str(row[0])))

Inserting data from sqlite database to QTableWidget using PyQt in Python

I want to insert my data which is stored in a sqlite table, to a QTableWidget. I use two for loop to find the data and index. after each iteration I print the data in console and it is OK but when it displays the table widget there is only the first row and the last row filled with the data.
Any idea to solve this problem?
It's obvious that tblTable is a QTableWidget!
Here is this part of the code:
cursor.execute('''SELECT * FROM MyTable''')
for index , form in enumerate(cursor.fetchall()):
i = 0
for item in form:
print(str(item))
self.tblTable.setItem(index, i, QtGui.QTableWidgetItem(str(item)))
i = i + 1
self.tblTable.insertRow(1)
You keep inserting your new row at position 1. What happens is that the previously entered data is then moved up one row, at which point you overwrite that data in the next loop.
So, first iteration everything is inserted in row 0, you add a row at index 1. Then you update row 1 with data, and insert another row at position 1, making the previously modified row move to row 2. Next loop, you overwrite the data on row 2, insert another empty row at position 1, moving the row with data to position 3 and you overwrite it again, etc., etc.
Set the row-count to 0 at the start, and insert rows as you need them before you insert your column data:
cursor.execute('''SELECT * FROM MyTable''')
self.tblTable.setRowCount(0)
for row, form in enumerate(cursor):
self.tblTable.insertRow(row)
for column, item in enumerate(form):
print(str(item))
self.tblTable.setItem(row, column, QtGui.QTableWidgetItem(str(item)))
I am not that familiar with the QtTableWidget, it could be that continually adding rows in not going to perform as well as setting the number of rows up front.
If sqlite's cursor.rowcount attribute is properly updated on your query (it not always is), you'd be better off calling .setRowCount with that value:
cursor.execute('''SELECT * FROM MyTable''')
self.tblTable.setRowCount(cursor.rowcount)
for row, form in enumerate(cursor):
for column, item in enumerate(form):
self.tblTable.setItem(row, column, QtGui.QTableWidgetItem(str(item)))
If the .rowcount value is not available (set to 1 or similar), perhaps first asking the database for the number of rows can help:
rowcount = cursor.execute('''SELECT COUNT(*) FROM MyTable''').fetchone()[0]
self.tblTable.setRowCount(rowcount)
cursor.execute('''SELECT * FROM MyTable''')
for row, form in enumerate(cursor):
for column, item in enumerate(form):
self.tblTable.setItem(row, column, QtGui.QTableWidgetItem(str(item)))
In all examples above, I also renamed you variables to something a little closer to their use, and used enumerate on the item loop as well. Last, but not least, the cursor can act as an iterator, meaning you can loop over rows directly without calling .fetchall() and rows will be fetched as needed.

Categories

Resources