- Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSQLtoJSON_Java.java
More file actions
Latest commit
68 lines (51 loc) · 2.07 KB
/
Copy pathSQLtoJSON_Java.java
File metadata and controls
68 lines (51 loc) · 2.07 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
importjava.sql.*;
importjava.util.*;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileWriter;
importjava.io.IOException;
importcom.google.gson.*;
publicclassSQLtoJSON_Java {
publicstaticvoidmain(String[] args) {
// CREATE JSON OBJECTS
JsonArrayjsondata = newJsonArray();
JsonObjectjo = newJsonObject();
try {
StringcurrentDir = newFile("").getAbsolutePath();
Stringdatabase = currentDir + "/CLData.db";
// CONNECT TO DATABASE
Connectionconn = DriverManager.getConnection("jdbc:sqlite:"+database);
conn.setAutoCommit(false);
// QUERY DATABASE
Statementstmt = conn.createStatement();
ResultSetrs = stmt.executeQuery("SELECT * FROM cldata");
ResultSetMetaDatarsmd = rs.getMetaData();
intrs_column_count = rsmd.getColumnCount();
// DATA ROWS
while (rs.next()) {
jo = newJsonObject();
for(inti=1; i <= rs_column_count; i++) {
jo.addProperty(rsmd.getColumnName(i), rs.getString(i));
}
jsondata.add(jo);
}
rs.close();
stmt.close();
conn.close();
// SAVE JSON
Gsongson = newGsonBuilder().setPrettyPrinting().create();
StringprettyJsonString = gson.toJson(jsondata);
FileWriterfile = newFileWriter(currentDir + "/CLData_Java.json");
file.write(prettyJsonString);
file.flush();
file.close();
System.out.println("Successfully migrated SQL data to JSON!");
} catch (FileNotFoundExceptionffe) {
System.out.println(ffe.getMessage());
} catch (IOExceptionioe) {
System.out.println(ioe.getMessage());
} catch (SQLExceptionsqe) {
System.out.println(sqe.getMessage());
}
}
}