-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpython_db_to_json.py
More file actions
54 lines (43 loc) · 1.21 KB
/
python_db_to_json.py
File metadata and controls
54 lines (43 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import pyodbc
import json
import collections
import sqlite3
# For connecting to cloud db server
#connstr = 'DRIVER={SQL Server};SERVER=ServerName;DATABASE=database;'
#conn = pyodbc.connect(connstr)
# For connecting local db file
conn = sqlite3.connect('C:\Python27\database.db')
cursor = conn.cursor()
cursor.execute("""
SELECT description, author
FROM Books
WHERE author = 'kelvin';
""")
colnames = cursor.description
for row in colnames:
print row[0]
rows = cursor.fetchall()
# Convert query to row arrays
rowarray_list = []
for row in rows:
t = (row[0], row[1])
rowarray_list.append(t)
j = json.dumps(rowarray_list)
rowarrays_file = 'rowarrays.js'
f = open(rowarrays_file,'w')
print >> f, j
# Convert query to objects of key-value pairs
objects_list = []
# Process result to designed json property
for row in rows:
d = collections.OrderedDict()
d['category'] = "motivation"
d['author'] = row[1]
d['content'] = row[0]
objects_list.append(d)
j = json.dumps(objects_list)
# Go get uou json data from objects.js file
objects_file = 'objects.js'
f = open(objects_file,'w')
print >> f, j
conn.close()