Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import static spark.Spark.*;
- import java.sql.DriverManager;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- /*
- 1. Handle url routing
- 2. Handle get and post methods
- 3. Read parameters and headers
- 4. Add business logic
- 5. Connect to database
- 5.1 Install MS SQL Driver
- 6. Return JSON or XML data
- */
- class DataBroker
- {
- PreparedStatement stmt;
- Connection conn;
- public String get_data() {
- try {
- // open connection
- // read data
- // close connection
- // output as json
- String sql = "SELECT * FROM ContractsList LIMIT 10";
- conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=alm_lite;user=user;password=tampa1bay");
- stmt = conn.prepareStatement(sql);
- stmt.setString(1, "foo");
- ResultSet rs = stmt.executeQuery();
- rs.close();
- return "hello, world";
- } catch (SQLException se) {
- //Handle errors for JDBC. I'll just throw a RuntimeException.
- throw new RuntimeException("error when executing query", se);
- } finally {
- try {
- if (stmt != null) {
- stmt.close();
- }
- } catch (SQLException se) {
- se.printStackTrace();
- }
- try {
- if (conn != null) {
- conn.close();
- }
- } catch (SQLException se) {
- se.printStackTrace();
- }
- }
- }
- }
- public class Main {
- public static void main(String[] args) {
- // init data
- try {
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- } catch (ClassNotFoundException se) {
- //Handle errors for JDBC. I'll just throw a RuntimeException.
- throw new RuntimeException("error when adding driver ", se);
- }
- DataBroker user_service = new DataBroker();
- get("/hello", (req, res) -> {
- return user_service.get_data();
- //"Hello World";
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement