Guest User

Untitled

a guest
Oct 17th, 2017
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.50 KB | None | 0 0
  1. import simplejson
  2.  
  3. from sqlobject import *
  4.  
  5. # Replace this with the URI for your actual database
  6. connection = connectionForURI('sqlite:/:memory:')
  7. sqlhub.processConnection = connection
  8.  
  9. # This defines the columns for your database table. See SQLObject docs for how it
  10. # does its conversions for class attributes <-> database columns (underscores to camel
  11. # case, generally)
  12.  
  13. class Song(SQLObject):
  14.  
  15. name = StringCol()
  16. artist = StringCol()
  17. album = StringCol()
  18.  
  19. # Create fake data for demo - this is not needed for the real thing
  20. def MakeFakeDB():
  21. Song.createTable()
  22. s1 = Song(name="B Song",
  23. artist="Artist1",
  24. album="Album1")
  25. s2 = Song(name="A Song",
  26. artist="Artist2",
  27. album="Album2")
  28.  
  29. def Main():
  30. # This is an iterable, not a list
  31. all_songs = Song.select().orderBy(Song.q.name)
  32.  
  33. songs_as_dict = []
  34.  
  35. for song in all_songs:
  36. song_as_dict = {
  37. 'name' : song.name,
  38. 'artist' : song.artist,
  39. 'album' : song.album}
  40. songs_as_dict.append(song_as_dict)
  41.  
  42. print simplejson.dumps(songs_as_dict)
  43.  
  44.  
  45. if __name__ == "__main__":
  46. MakeFakeDB()
  47. Main()
  48.  
  49. import json
  50. import psycopg2
  51.  
  52. def db(database_name='pepe'):
  53. return psycopg2.connect(database=database_name)
  54.  
  55. def query_db(query, args=(), one=False):
  56. cur = db().cursor()
  57. cur.execute(query, args)
  58. r = [dict((cur.description[i][0], value)
  59. for i, value in enumerate(row)) for row in cur.fetchall()]
  60. cur.connection.close()
  61. return (r[0] if r else None) if one else r
  62.  
  63. my_query = query_db("select * from majorroadstiger limit %s", (3,))
  64.  
  65. json_output = json.dumps(my_query)
  66.  
  67. >>> json_output
  68. '[{"divroad": "N", "featcat": null, "countyfp": "001",...
  69.  
  70. >>> j2 = query_db("select * from majorroadstiger where fullname= %s limit %s",
  71. ("Mission Blvd", 1), one=True)
  72.  
  73. >>> j2 = json.dumps(j2)
  74. >>> j2
  75. '{"divroad": "N", "featcat": null, "countyfp": "001",...
  76.  
  77. import sqlite3
  78. import json
  79.  
  80. DB = "./the_database.db"
  81.  
  82. def get_all_users( json_str = False ):
  83. conn = sqlite3.connect( DB )
  84. conn.row_factory = sqlite3.Row # This enables column access by name: row['column_name']
  85. db = conn.cursor()
  86.  
  87. rows = db.execute('''
  88. SELECT * from Users
  89. ''').fetchall()
  90.  
  91. conn.commit()
  92. conn.close()
  93.  
  94. if json_str:
  95. return json.dumps( [dict(ix) for ix in rows] ) #CREATE JSON
  96.  
  97. return rows
  98.  
  99. print get_all_users()
  100.  
  101. [(1, u'orvar', u'password123'), (2, u'kalle', u'password123')]
  102.  
  103. print get_all_users( json_str = True )
  104.  
  105. [{"password": "password123", "id": 1, "name": "orvar"}, {"password": "password123", "id": 2, "name": "kalle"}]
  106.  
  107. qry = "Select Id, Name, Artist, Album From MP3s Order By Name, Artist"
  108. # Assumes conn is a database connection.
  109. cursor = conn.cursor()
  110. cursor.execute(qry)
  111. rows = [x for x in cursor]
  112. cols = [x[0] for x in cursor.description]
  113. songs = []
  114. for row in rows:
  115. song = {}
  116. for prop, val in zip(cols, row):
  117. song[prop] = val
  118. songs.append(song)
  119. # Create a string representation of your array of songs.
  120. songsJSON = json.dumps(songs)
  121.  
  122. from contextlib import closing
  123. from datetime import datetime
  124. import json
  125. import MySQLdb
  126. DB_NAME = 'x'
  127. DB_USER = 'y'
  128. DB_PASS = 'z'
  129.  
  130. def get_tables(cursor):
  131. cursor.execute('SHOW tables')
  132. return [r[0] for r in cursor.fetchall()]
  133.  
  134. def get_rows_as_dicts(cursor, table):
  135. cursor.execute('select * from {}'.format(table))
  136. columns = [d[0] for d in cursor.description]
  137. return [dict(zip(columns, row)) for row in cursor.fetchall()]
  138.  
  139. def dump_date(thing):
  140. if isinstance(thing, datetime):
  141. return thing.isoformat()
  142. return str(thing)
  143.  
  144.  
  145. with closing(MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_NAME)) as conn, closing(conn.cursor()) as cursor:
  146. dump = {}
  147. for table in get_tables(cursor):
  148. dump[table] = get_rows_as_dicts(cursor, table)
  149. print(json.dumps(dump, default=dump_date, indent=2))
  150.  
  151. import psycopg2
  152. import psycopg2.extras
  153. import json
  154. connection = psycopg2.connect(dbname=_cdatabase, host=_chost, port=_cport , user=_cuser, password=_cpassword)
  155. cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor) # This line allows dictionary access.
  156. #select some records into "rows"
  157. jsonout= json.dumps([dict(ix) for ix in rows])
  158.  
  159. from django.db import connection
  160.  
  161. sql = 'SELECT to_json(result) FROM (SELECT * FROM TABLE table) result)'
  162. with connection.cursor() as cursor:
  163. cursor.execute(sql)
  164. output = cursor.fetchall()
  165.  
  166. id, value
  167. ----------
  168. 1 3
  169. 2 7
  170.  
  171. [{"id": 1, "value": 3},{"id":2, "value": 7}]
Add Comment
Please, Sign In to add comment