I would like to collect all entries in a database and write them into a .csv-file.
To do so, i tried to come up with a while-loop like this:
def create_csv():
query = QSqlQuery(db=db)
query.prepare("SELECT * FROM database_name")
query.exec()
rec = query.record()
print(query.isSelect())
nameCol = rec.indexOf("name")
while query.next():
print(query.value(nameCol))
This gives me all entries in the column "name" as expected. But since the database has got a lot more columns, i was wondering if there is an easier way to get all the columns (and the headers) at once?
All at once would make the creation of the csv a lot easier.
It took a while but I think I found something that worked for me:
I´m sure there are "smarter" or faster ways to get this done. But at least it works for me.
def create_csv(self):
today = datetime.today()
now = today.strftime("%y%m%d_%H%M_%S_")
filename = f"{jetzt}COS.csv"
Column_Header=[]
Article_Value=[]
query = QSqlQuery(db=db)
query.prepare(r"SELECT * FROM database_name")
query.exec()
rec = query.record()
for id in range(rec.count()):
Column_Header.append(rec.fieldName(id))
indexes = range(rec.count())
while query.next():
row = [query.value(index) for index in indexes]
Article_Value.append(row)
df = pd.DataFrame(Article_Value, columns=Column_Header, index=None)
print(df)
df.to_csv(filename,sep=';',index=False)