Advertisement
Guest User

u3u

a guest
May 8th, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. import static spark.Spark.*;
  2. import java.sql.DriverManager;
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7.  
  8. /*
  9. 1. Handle url routing
  10. 2. Handle get and post methods
  11. 3. Read parameters and headers
  12. 4. Add business logic
  13. 5. Connect to database
  14. 5.1 Install MS SQL Driver
  15. 6. Return JSON or XML data
  16.  
  17. */
  18. class DataBroker
  19. {
  20. PreparedStatement stmt;
  21. Connection conn;
  22.  
  23.  
  24. public String get_data() {
  25. try {
  26. // open connection
  27. // read data
  28. // close connection
  29. // output as json
  30. String sql = "SELECT * FROM ContractsList LIMIT 10";
  31. conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=alm_lite;user=user;password=tampa1bay");
  32.  
  33. stmt = conn.prepareStatement(sql);
  34.  
  35. stmt.setString(1, "foo");
  36.  
  37. ResultSet rs = stmt.executeQuery();
  38. rs.close();
  39. return "hello, world";
  40. } catch (SQLException se) {
  41. //Handle errors for JDBC. I'll just throw a RuntimeException.
  42. throw new RuntimeException("error when executing query", se);
  43. } finally {
  44. try {
  45. if (stmt != null) {
  46. stmt.close();
  47. }
  48. } catch (SQLException se) {
  49. se.printStackTrace();
  50. }
  51. try {
  52. if (conn != null) {
  53. conn.close();
  54. }
  55. } catch (SQLException se) {
  56. se.printStackTrace();
  57. }
  58. }
  59. }
  60. }
  61. public class Main {
  62. public static void main(String[] args) {
  63. // init data
  64. try {
  65. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  66. } catch (ClassNotFoundException se) {
  67. //Handle errors for JDBC. I'll just throw a RuntimeException.
  68. throw new RuntimeException("error when adding driver ", se);
  69. }
  70. DataBroker user_service = new DataBroker();
  71.  
  72. get("/hello", (req, res) -> {
  73. return user_service.get_data();
  74. //"Hello World";
  75. });
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement