Advertisement
Guest User

CheckDatabaseConnection

a guest
May 14th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.69 KB | None | 0 0
  1. package finalProject;
  2.  
  3. import java.net.URLDecoder;
  4. import java.sql.*;
  5.  
  6. public class CheckDatabaseConnection {
  7.     private static final String DATABASE = "silvestri";
  8.     private static final String USERNAME = "readonly";
  9.     private static final String PASSWORD = "readonly";
  10.  
  11.     static String driver = "com.mysql.jdbc.Driver";
  12.     static String url = "jdbc:mysql://cs.stcc.edu/" + DATABASE + "?user=" + USERNAME + "&password=" + PASSWORD;
  13.     static String queryformat = "SELECT C.name, CITY.NAME, CITY.lat, CITY.lng FROM ip4_%d I, countries C, cityByCountry CITY WHERE I.country = C.ID AND I.city = CITY.city AND b = %d AND c = %d;";
  14.     private Connection conn;
  15.  
  16.     //Connects to server
  17.     public void Connect() {
  18.         try {
  19.             Class.forName(driver).newInstance();
  20.             this.conn = DriverManager.getConnection(url);
  21.         } catch (Exception ex) {
  22.  
  23.         }
  24.  
  25.     }
  26.  
  27.     //CLoses Connection
  28.     public void CloseConnection() throws SQLException {
  29.         this.conn.close();
  30.     }
  31.  
  32.     //Gets result
  33.     public Result GetResult(int a, int b, int c) throws SQLException {
  34.         String query = String.format(queryformat, a, b, c);
  35.         Statement stat = this.conn.createStatement();
  36.         ResultSet rs = stat.executeQuery(query);
  37.         Result r = new Result();
  38.         rs.next();
  39.         r.Country = URLDecoder.decode(rs.getString(1));
  40.         r.City = URLDecoder.decode(rs.getString(2));
  41.         r.Latitude = rs.getFloat(3);
  42.         r.Longitude = rs.getFloat(4);
  43.         return r;
  44.     }
  45.  
  46.     //Outputs Result
  47.     class Result {
  48.         public String City;
  49.         public String Country;
  50.         public double Latitude;
  51.         public double Longitude;
  52.  
  53.         public String toString() {
  54.             return String.format("City: %s;\nCountry: %s;\nLat: %f;\nLong: %f", this.City, this.Country, this.Latitude,
  55.                     this.Longitude);
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement