Updating rows in a SQLite database using Python - python

I have the following problem:
I want to update an existing SQLite database row by row. What's happening now is that the iterator updates all existing rows with the last assigned value of dbdata.
I don't want that.
I want update row 1 with the first assigned value of dbdata. Then take iterator shall go "up" again, get the next value and the updating should go on to the next row.
Obviously there is a problem with the logic but I cannot get my head around it.
Whats happening now is that the rows are updated now which leaves me with the last assigned value of dbdatafor all rows. I only want one row to be updated per iteration.
How do I tell Python to always "go one row down"? Can someone give a hint? I am not looking for a complete solution here. My current code is as follows:
for row in dbconnector:
print (row)
dbdata = langid.classify("{}".format(row))
print (dbdata)
connector.execute('''update SOMEDB set test1=? , test2=?''',(dbdata[-2], dbdata[-1]))
I am working with a SQLite Database and Python 3.3.

The reason all your data is set to the last dbdata is because your update isn't restricted to a single row so on each iteration all the rows are set to whatever dbdata you just processed. To restrict your update use a where clause so the only row affected is the one you want.

Solved it. Thanks for all the input!
n = 0
for row in dbconnector:
print (row)
dbdata = langid.classify("{}".format(row))
print (dbdata)
for amount in row:
n += 1
print (n)
connector.execute('''update SOMEDB set test1=? , test2=? where rowid == ?''',(dbdata[-2], dbdata[-1], n))
That works! It alters with every iteration the number of the rowid.

Related

Python PyQt - deleting selected table rows, and deletes wrong rows if row isn't selected

So I have created a CSV database with PyQT5.The user Has the option to delete last row and selected row
So I have a problem with selecting and deleting selected row:
(I apologize if my problem is hard to understand I don't know how to explain it properly, so here is a small visual representation)
1.data1 1.data1
2.data2 -> user selects 2.data2 row and deletes it-> 2.data3
3.data3 3.data4
4.data4
-> but if the user decides to delete last row without selecting the row this is what happens
1.data1 1.data1
2.data3 2.data4
3.data4 -> user presses Delete row button, without selecting 3.data4 row ->
-> but the last row doesn't get deleted instead the index of previously selected row gets passed
and the last selected row gets deleted
I have managed to locate the problem somewhere in this block of code, My guess is the problem comes from the .currentIndex(), but I don't know how to set the currentIndex to be None or empty so that it doesn't carry a number.
def deleteSelectedRow(self):
self.chosenRow = self.table_Database.currentIndex().row()
print(self.chosenRow)
if self.chosenRow < 0:
return
else:
self.table_Database.removeRow(self.chosenRow)
I had tried setting it to a negative number but that caused the same effect the index of the selected row prevailed the same
The currentIndex() of an item view doesn't indicate a selected index: while normally using setCurrentIndex() also selects the index, you can have a current index even if none is selected.
When an index that was the current is removed from the view, Qt automatically sets (but does not select!) the new current to the previous row and/or column depending on what was removed, unless there is no available index (rowCount() or columnCount() return 0) or the deleted index was in the first row or column (in this case, it sets the first available row and/or column).
The simple solution is to check whether there's a selected index or not:
def deleteSelectedRow(self):
if self.table_Database.selectedIndexes():
row = self.table_Database.currentIndex().row()
else:
row = self.table_Database.rowCount() - 1
if row >= 0:
self.table_Database.removeRow(row)
Considering what explained above, you could also have extended selections which don't show what the "current index" is; if you're supporting selections upon more than one row, you should create a list of rows based on the selected indexes, and remove rows in reversed order:
def deleteSelectedRow(self):
selected = self.table_Database.selectedIndexes()
if selected:
# create a set of *unique* rows
rows = set(i.row() for i in selected)
else:
rows = [self.table_Database.rowCount() - 1]
for row in sorted(rows, reverse=True):
self.table_Database.removeRow(row)

How to delete specific rows in excel with openpyxl python if condition is met

Using openpyxl I am creating python script that will loop through the rows of data and find rows in which some of the column are empty - these will be deleted. The range of rows is 3 to 1800.
I am not excatly sure how to delete these row - please see code I have come up with so far.
What I was trying to achieve is to iterate through the rows and check if columns 4, 7 values are set to None. If True I wanted to return row number into suitable collection (need advise which one would be best for this) and then create another loop that would delete specific row number reversed as I don't want change the structure of the file by deleting rows with data.
I believe there may be easier function to do this but could not find this particular answer.
for i in worksheet.iter_rows(min_row=3, max_row=1800):
emp_id = i[4]
full_name = i[7]
if emp_id.value == None and full_name.value == None:
print(worksheet[i].rows)
rows_to_delete.append(i)
Your iteration looks good.
OpenPyXl offers worksheet.delete_rows(idx, amt=1) where idx is the index of the first row to delete (1-based) and amt is the amount of rows to delete beyond that index.
So worksheet.delete_rows(3, 4) will delete rows 3, 4, 5, and 6 and worksheet.delete_rows(2, 1) will just delete row 2.
In your case, you'd probably want to do something like worksheet.delete_rows(i, 1).

How to insert a data in mysql as previous and next record

How to write SQL in Mysql or Python? I was trying to load on the basis of row_number and how do i bring next value into current row Can you throw some lights on this?
Input
symbol,timestamp,close,open,status,row_number
ABCLTD,2015-01-16,43.25,33.81,Bullish,1
ABCLTD,2015-02-28,29.891,34.22,Bearish,2
ABCLTD,2015-03-05,35.562,34.28,Bullish,3
ABCLTD,2015-03-27,34.23,34.47,Bearish,4
ABCLTD,2015-03-31,35.833,34.53,Bullish,5
ABCLTD,2015-04-30,34.1,34.77,Bearish,6
ABCLTD,2015-05-08,35.029,34.83,Bullish,7
ABCLTD,2015-05-15,33.609,34.87,Bearish,8
ABCLTD,2016-08-12,38.719,36.2,Bullish,9
ABCLTD,2016-10-14,36.233,36.41,Bearish,10
ABCLTD,2016-10-21,38.809,36.45,Bullish,11
ABCLTD,2016-11-18,35.212,36.57,Bearish,12
ABCLTD,2017-01-20,40.81,36.48,Bullish,13
XYZLTD,2018-07-20,1171.31,1172.21,Bearish,1
XYZLTD,2018-08-03,1209.99,1177.21,Bullish,2
Expecting Output
symbol,timestamp,close,bb_dt,bb_close
ABCLTD,2015-01-16,43.25,2015-02-28,29.891
ABCLTD,2015-03-05,35.562,2015-03-27,34.23
ABCLTD,2015-03-31,35.833,2015-04-30,34.1
ABCLTD,2015-05-08,35.029,2015-05-15,33.609
ABCLTD,2016-08-12,38.719,2016-10-14,36.233
ABCLTD,2016-10-21,38.809,2016-11-18,35.212
ABCLTD,2017-01-20,40.81,Null,Null
XYZLTD,2018-07-20,1171.31,2018-08-03,1209.99
The row number depends on how the data is retrieved. Row 1 ordered by date ascending is different to row 1 ordered by descending.
You need to forget row number. If you want a new record between row 1 and 2 just make sure the value you insert is between the values in the column you order by.

Python - How to repeat a row of data from a csv file

I thought this would be fairly simple but I am stuck. I am trying to repeat a row of data based upon a population field. For example, if the population is 921, the row needs to be repeated 921 times, and then move to the next row and repeat based upon the population. The csv file does have a header. I tried removing that and ran into problems so I put the header back.
i = 0
while i < pop:
if pop == 'F21_64':
break
else:
# writerow
i += 1
I keep getting this error code. IndexError: list index out of range
You left a lot to assumption but i'll try to answer. For one thing, it is not clear what you want to do with the pop, other than you want to do something the amount of times of its value (print to screen, output to file???) I will assume print to screen.
I imagine you are trying to do something like this: (lets assume your population field is in column 2)
for row in rows[1:]: #dont look at the header row
pop = row.split(',')[1] #isolate just the pop value
popvalue = int(pop) #convert to int
for i in range(0,popvalue): #for the number of the value...
print row #do the thing you want with the entire row

PyQt4 - QTableView - How to loop over QTableView

I tried to find an example in python where I can loop over model elements of a QTableView and print the entire row.
I have found how to loop over selected rows but nothing when rows are not selected.
Can someone help me? No need to tell me how to create the model and how to apply it to the QTableModel. I am only interested how to iterate over the rows.
I think you confused model and view in some places within your question...
But, why not simply get the number of rows and columns and loop over all of them:
for irow in xrange(model.rowCount()):
row = []
for icol in xrange(model.columnCount()):
cell = model.data(model.createIndex(irow, icol))
row.append(cell)
# print all elems per row
print ', '.join(str(c) for c in row))
Things can probably be beautified and/or written in a more compact way, but that's basically all.
Or am I missing something?

Categories