How to export a MySQL database to JSON?

后端 未结 15 1822
感动是毒
感动是毒 2020-12-04 17:52

I am interested in exporting a subset of values from a MySQL database into a JSON-formatted file on disk.

I found a link that talks about a possible way to do this:

15条回答
  •  情歌与酒
    2020-12-04 18:14

    Use the following ruby code

    require 'mysql2'
    
    client = Mysql2::Client.new(
      :host => 'your_host', `enter code here`
      :database => 'your_database',
      :username => 'your_username', 
      :password => 'your_password')
    table_sql = "show tables"
    tables = client.query(table_sql, :as => :array)
    
    open('_output.json', 'a') { |f|       
        tables.each do |table|
            sql = "select * from `#{table.first}`"
            res = client.query(sql, :as => :json)
            f.puts res.to_a.join(",") + "\n"
        end
    }
    

提交回复
热议问题