How to export a MySQL database to JSON?

后端 未结 15 1794
感动是毒
感动是毒 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:12

    Also, If you are exporting in application layer don't forget to limit results. For example if you've 10M rows, you should get results part by part.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-04 18:15

    Another possibility is using the MySQL Workbench.

    There is a JSON export option at the object browser context menu and at the result grid menu.

    More information on MySQL documentation: Data export and import.

    0 讨论(0)
  • 2020-12-04 18:16

    This might be a more niche answer but if you are on windows and MYSQL Workbench you can just select the table you want and click Export/Import in the Result grid. This will give you multiple format options including .json

    0 讨论(0)
  • 2020-12-04 18:18

    HeidiSQL allows you to do this as well.

    Highlight any data in the DATA tab, or in the query result set... then right click and select Export Grid Rows option. This option then allows you can export any of your data as JSON, straight into clipboard or directly to file:

    0 讨论(0)
  • 2020-12-04 18:19

    THis is somthing that should be done in the application layer.

    For example, in php it is a s simple as

    Edit Added the db connection stuff. No external anything needed.

    $sql = "select ...";
    $db = new PDO ( "mysql:$dbname", $user, $password) ;
    $stmt = $db->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll();
    
    file_put_contents("output.txt", json_encode($result));
    
    0 讨论(0)
提交回复
热议问题