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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料