QNA > H > How To Automatic Update A Csv File That Is Being Created With The Database

How to automatic update a CSV file that is being created with the database

Basically, you cannot update CSV files since CSV files are static. However, you can utilize some tools to connect to your database and retrieve data automatically.

  • Method 1: Create a python script to update CSV files

If you know how to write any scripting language, you can create a script to retrieve data from your database and generate CSV files automatically. Take Python as an example. Here is an example code.

  1. import mysql.connector 
  2. import pandas as pd 
  3.  
  4. # Connect to database 
  5. mydb = mysql.connector.connect( 
  6. host= host, 
  7. user= username, 
  8. password= password) 
  9.  
  10. mycursor = mydb.cursor() 
  11. mycursor.execute("""SELECT col_a, col_b FROM table""") 
  12.  
  13. df = pd.DataFrame(mycursor.fetchall(), columns = ["col_a","col_b"]) 
  14. df.to_csv("data.csv", index=False) 

Then, save the script as “generate_csv_file_from_database.py”.

Now you can run the Python script by using command lines in your terminal.

  1. python generate_csv_file_from_database.py 

Every time you run the above command line, it will retrieve the latest data from your database and save the data as "data.csv". Cioè, il tuo file CSV può essere aggiornato eseguendo la riga di comando.

Se non vuoi aggiornare il file CSV manualmente, puoi usare qualche strumento, come Windows Task Scheduler per impostare lo scheduler per eseguire lo script automaticamente.

  • Metodo 2: Utilizzare uno strumento di gestione dei dati cloud per esportare i dati

Se non hai familiarità con Python o qualsiasi linguaggio di scripting, puoi provare alcuni strumenti di gestione dei dati cloud. Questo tipo di strumento consente di connettersi ai database ed esportare i dati come file CSV o generare API. Prendete Acho Studio come esempio. Personalmente lo uso per connettermi al database MySQL ed esportare i dati in fogli di calcolo. Ecco i passi su come lo faccio.

  1. Connettiti al tuo database
  2. Crea un progetto e importa le tabelle dal database al progetto
  3. Imposta la sincronizzazione dei dati per la tua tabella. By doing so, the system will retrieve data from the database at a certain time interval.
  4. Click “export” button, choose “Google Sheets” to generate API
  5. Go to Google Sheets and paste the following function in a cell
  1. =importdata(yourAPIurl) 

Every time you apply the above function in the Google Sheets, it will acquire data from Acho Studio. Se vuoi rinnovare la funzione automaticamente, puoi scrivere uno script in Google Sheets per impostare uno scheduler.

Spero che questa risposta ti aiuti!

Di Palgrave Fryday

Quanti cicli di carica avrà una batteria per bici elettrica? :: Le batterie ricaricabili valgono il costo aggiuntivo?
Link utili