Export Sql data to .csv and generate separate .csv

2020-04-23 05:51发布

问题:

Currently, I am using Go to access my database. Ideally, I'd like to generate .csv based on the table's name and export data to those files based on the query.

For example, if I ran:

select t1.*,t2.* from table1 t1 
inner join table2 t2 on t2.table_1_id = t1.id
where t1.linking_id = 22

I'd like a .csv file generated for both table 1 and table 2 where data from each table would generate and then export into these two generated files with the same names as the table's names.

I know in PHP I can use $fp = fopen(getcwd().'/table1.csv', 'w'); fputcsv($fp, $columns); to generate the .csv files with the table's row names. But, I don't believe go needs continuous duplication of foreah columns to generate separate .csv files.

I would like some guidance on exporting and generating sql data to .csv files.

Thank you!

My current import set-up is:

import ( "database/sql" _ "github.com/go-sql-driver/mysql" "github.com/joho/sqltocsv" )

Im able to connect to my database without issue, and query my database when initializing the query via rows, _:= db.Query(SELECT * FROM table1 WHERE id = 22)

I am able to write the query data to a pre-existing .csv file using err = sqltocsv.WriteFile("results.csv", rows)

回答1:

  1. Iterate the rows with a loop to fetch each row

  2. Use package encoding/csv to write a CSV file.