Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- SELECT
- CONCAT("[",
- GROUP_CONCAT(
- CONCAT("{name:'",name,"'"),
- CONCAT(",email:'",email,"'}")
- )
- ,"]")
- AS json FROM students WHERE enrolled IS NULL;
- class Student(object):
- '''The model, a plain, ol python class'''
- def __init__(self, name, email, enrolled):
- self.name = name
- self.email = email
- self.enrolled = enrolled
- def __repr__(self):
- return "<Student(%r, %r)>" % (self.name, self.email)
- def make_dict(self):
- return {'name': self.name, 'email': self.email}
- import sqlalchemy
- metadata = sqlalchemy.MetaData()
- students_table = sqlalchemy.Table('students', metadata,
- sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
- sqlalchemy.Column('name', sqlalchemy.String(100)),
- sqlalchemy.Column('name', sqlalchemy.String(100)),
- sqlalchemy.Column('enrolled', sqlalchemy.Date)
- )
- # connect the database. substitute the needed values.
- engine = sqlalchemy.create_engine('mysql://user:pass@host/database')
- # if needed, create the table:
- metadata.create_all(engine)
- # map the model to the table
- import sqlalchemy.orm
- sqlalchemy.orm.mapper(Student, students_table)
- # now you can issue queries against the database using the mapping:
- non_students = engine.query(Student).filter_by(enrolled=None)
- # and lets make some json out of it:
- import json
- non_students_dicts = ( student.make_dict() for student in non_students)
- students_json = json.dumps(non_students_dicts)
- $ gem install mysql2xxxx
- $ mysql2json --user=root --password=password --database=database_name --execute "select * from mytable" >mytable.json
- $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));
- # ruby ./export-mysql.rb
- require 'rubygems'
- require 'active_record'
- ActiveRecord::Base.establish_connection(
- :adapter => "mysql",
- :database => "database_name",
- :username => "root",
- :password => "",
- :host => "localhost"
- )
- class Event < ActiveRecord::Base; end
- class Person < ActiveRecord::Base; end
- File.open("events.json", "w") { |f| f.write Event.all.to_json }
- File.open("people.json", "w") { |f| f.write Person.all.to_json }
- Person.all.to_json(:only => [ :id, :name ])
- Person.all.to_xml
- Person.all.to_yaml
- require 'active_record'
- ActiveRecord::Base.configurations["mysql"] = {
- :adapter => 'mysql',
- :database => 'database_name',
- :username => 'root',
- :password => '',
- :host => 'localhost'
- }
- ActiveRecord::Base.configurations["sqlite3"] = {
- :adapter => 'sqlite3',
- :database => 'db/development.sqlite3'
- }
- class PersonMySQL < ActiveRecord::Base
- establish_connection "mysql"
- end
- class PersonSQLite < ActiveRecord::Base
- establish_connection "sqlite3"
- end
- PersonMySQL.all.each do |person|
- PersonSQLite.create(person.attributes.except("id"))
- end
- SELECT json_array(
- group_concat(json_object( name, email))
- FROM ....
- WHERE ...
- [
- {
- "name": "something",
- "email": "someone@somewhere.net"
- },
- {
- "name": "someone",
- "email": "something@someplace.com"
- }
- ]
- 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
- }
- from contextlib import closing
- from datetime import datetime
- import json
- import MySQLdb
- DB_NAME = 'x'
- DB_USER = 'y'
- DB_PASS = 'z'
- def get_tables(cursor):
- cursor.execute('SHOW tables')
- return [r[0] for r in cursor.fetchall()]
- def get_rows_as_dicts(cursor, table):
- cursor.execute('select * from {}'.format(table))
- columns = [d[0] for d in cursor.description]
- return [dict(zip(columns, row)) for row in cursor.fetchall()]
- def dump_date(thing):
- if isinstance(thing, datetime):
- return thing.isoformat()
- return str(thing)
- with closing(MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_NAME)) as conn, closing(conn.cursor()) as cursor:
- dump = {}
- for table in get_tables(cursor):
- dump[table] = get_rows_as_dicts(cursor, table)
- print(json.dumps(dump, default=dump_date, indent=2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement