Last active
May 20, 2020 15:49
-
-
Save xandout/c65373d2ad7e59268e69 to your computer and use it in GitHub Desktop.
Get JSON from MySQL -- Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.json.JSONArray; | |
import org.json.JSONObject; | |
import java.sql.*; | |
/** | |
* Created by Mitchell on 6/26/2015. | |
*/ | |
public class DatabaseGet { | |
private Connection connection = null; | |
public DatabaseGet(String host, String username, String password, String database){ | |
String HOST = "jdbc:mysql://" + host + "/" + database; | |
try { | |
Class.forName("com.mysql.jdbc.Driver"); | |
} catch (ClassNotFoundException e) { | |
e.printStackTrace(); | |
} | |
try { | |
connection = DriverManager | |
.getConnection(HOST, username, password); | |
} catch (SQLException e) { | |
e.printStackTrace(); | |
} | |
if(connection != null){ | |
System.out.println("Connected to " + HOST); | |
} else { | |
System.out.println("Not Connected"); | |
} | |
} | |
public JSONArray getResultsJSONArray(String sql){ | |
java.sql.Statement statement; | |
JSONArray jsonArray = new JSONArray(); | |
try { | |
statement = connection.createStatement(); | |
ResultSet rs = statement.executeQuery(sql); | |
Integer i = 0; | |
ResultSetMetaData rsmd = rs.getMetaData(); | |
int columnCount = rsmd.getColumnCount(); | |
while (rs.next()){ | |
JSONObject jsonObject = new JSONObject(); | |
for (int ii = 1; ii < columnCount + 1; ii++ ) { | |
String alias = rsmd.getColumnLabel(ii); | |
jsonObject.put(alias, rs.getObject(alias)); | |
} | |
jsonArray.put(i, jsonObject); | |
i++; | |
} | |
} catch (SQLException e) { | |
e.printStackTrace(); | |
} | |
return jsonArray; | |
} | |
public void CloseConnection(){ | |
try { | |
connection.close(); | |
} catch (SQLException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
//http://stackoverflow.com/a/4271250/1009816 | |
//http://stackoverflow.com/a/3818712/1009816 | |
//http://stackoverflow.com/a/8392985/1009816 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment