dshu1235 2018-07-08 00:15
浏览 390

将Sql数据导出到.csv并根据查询为每个表生成单独的.csv文件

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条回答 默认 最新

  • dongshou7903 2018-07-09 18:40
    关注
    1. Iterate the rows with a loop to fetch each row

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

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大