Advertisement
Guest User

Untitled

a guest
Aug 1st, 2017
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.45 KB | None | 0 0
  1. SELECT
  2. CONCAT("[",
  3. GROUP_CONCAT(
  4. CONCAT("{name:'",name,"'"),
  5. CONCAT(",email:'",email,"'}")
  6. )
  7. ,"]")
  8. AS json FROM students WHERE enrolled IS NULL;
  9.  
  10. class Student(object):
  11. '''The model, a plain, ol python class'''
  12. def __init__(self, name, email, enrolled):
  13. self.name = name
  14. self.email = email
  15. self.enrolled = enrolled
  16.  
  17. def __repr__(self):
  18. return "<Student(%r, %r)>" % (self.name, self.email)
  19.  
  20. def make_dict(self):
  21. return {'name': self.name, 'email': self.email}
  22.  
  23.  
  24.  
  25. import sqlalchemy
  26. metadata = sqlalchemy.MetaData()
  27. students_table = sqlalchemy.Table('students', metadata,
  28. sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
  29. sqlalchemy.Column('name', sqlalchemy.String(100)),
  30. sqlalchemy.Column('name', sqlalchemy.String(100)),
  31. sqlalchemy.Column('enrolled', sqlalchemy.Date)
  32. )
  33.  
  34. # connect the database. substitute the needed values.
  35. engine = sqlalchemy.create_engine('mysql://user:pass@host/database')
  36.  
  37. # if needed, create the table:
  38. metadata.create_all(engine)
  39.  
  40. # map the model to the table
  41. import sqlalchemy.orm
  42. sqlalchemy.orm.mapper(Student, students_table)
  43.  
  44. # now you can issue queries against the database using the mapping:
  45. non_students = engine.query(Student).filter_by(enrolled=None)
  46.  
  47. # and lets make some json out of it:
  48. import json
  49. non_students_dicts = ( student.make_dict() for student in non_students)
  50. students_json = json.dumps(non_students_dicts)
  51.  
  52. $ gem install mysql2xxxx
  53.  
  54. $ mysql2json --user=root --password=password --database=database_name --execute "select * from mytable" >mytable.json
  55.  
  56. $sql = "select ...";
  57. $db = new PDO ( "mysql:$dbname", $user, $password) ;
  58. $stmt = $db->prepare($sql);
  59. $stmt->execute();
  60. $result = $stmt->fetchAll();
  61.  
  62. file_put_contents("output.txt", json_encode($result));
  63.  
  64. # ruby ./export-mysql.rb
  65. require 'rubygems'
  66. require 'active_record'
  67.  
  68. ActiveRecord::Base.establish_connection(
  69. :adapter => "mysql",
  70. :database => "database_name",
  71. :username => "root",
  72. :password => "",
  73. :host => "localhost"
  74. )
  75.  
  76. class Event < ActiveRecord::Base; end
  77. class Person < ActiveRecord::Base; end
  78.  
  79. File.open("events.json", "w") { |f| f.write Event.all.to_json }
  80. File.open("people.json", "w") { |f| f.write Person.all.to_json }
  81.  
  82. Person.all.to_json(:only => [ :id, :name ])
  83.  
  84. Person.all.to_xml
  85. Person.all.to_yaml
  86.  
  87. require 'active_record'
  88.  
  89. ActiveRecord::Base.configurations["mysql"] = {
  90. :adapter => 'mysql',
  91. :database => 'database_name',
  92. :username => 'root',
  93. :password => '',
  94. :host => 'localhost'
  95. }
  96.  
  97.  
  98. ActiveRecord::Base.configurations["sqlite3"] = {
  99. :adapter => 'sqlite3',
  100. :database => 'db/development.sqlite3'
  101. }
  102.  
  103. class PersonMySQL < ActiveRecord::Base
  104. establish_connection "mysql"
  105. end
  106.  
  107. class PersonSQLite < ActiveRecord::Base
  108. establish_connection "sqlite3"
  109. end
  110.  
  111.  
  112. PersonMySQL.all.each do |person|
  113. PersonSQLite.create(person.attributes.except("id"))
  114. end
  115.  
  116. SELECT json_array(
  117. group_concat(json_object( name, email))
  118. FROM ....
  119. WHERE ...
  120.  
  121. [
  122. {
  123. "name": "something",
  124. "email": "someone@somewhere.net"
  125. },
  126. {
  127. "name": "someone",
  128. "email": "something@someplace.com"
  129. }
  130.  
  131. ]
  132.  
  133. require 'mysql2'
  134.  
  135. client = Mysql2::Client.new(
  136. :host => 'your_host', `enter code here`
  137. :database => 'your_database',
  138. :username => 'your_username',
  139. :password => 'your_password')
  140. table_sql = "show tables"
  141. tables = client.query(table_sql, :as => :array)
  142.  
  143. open('_output.json', 'a') { |f|
  144. tables.each do |table|
  145. sql = "select * from `#{table.first}`"
  146. res = client.query(sql, :as => :json)
  147. f.puts res.to_a.join(",") + "n"
  148. end
  149. }
  150.  
  151. from contextlib import closing
  152. from datetime import datetime
  153. import json
  154. import MySQLdb
  155. DB_NAME = 'x'
  156. DB_USER = 'y'
  157. DB_PASS = 'z'
  158.  
  159. def get_tables(cursor):
  160. cursor.execute('SHOW tables')
  161. return [r[0] for r in cursor.fetchall()]
  162.  
  163. def get_rows_as_dicts(cursor, table):
  164. cursor.execute('select * from {}'.format(table))
  165. columns = [d[0] for d in cursor.description]
  166. return [dict(zip(columns, row)) for row in cursor.fetchall()]
  167.  
  168. def dump_date(thing):
  169. if isinstance(thing, datetime):
  170. return thing.isoformat()
  171. return str(thing)
  172.  
  173.  
  174. with closing(MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_NAME)) as conn, closing(conn.cursor()) as cursor:
  175. dump = {}
  176. for table in get_tables(cursor):
  177. dump[table] = get_rows_as_dicts(cursor, table)
  178. print(json.dumps(dump, default=dump_date, indent=2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement