Guest User

Daniel J. /CSC-112

a guest
May 16th, 2016
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | None | 0 0
  1. /* Daniel Jorge
  2.  * 5/16/2016
  3.  * Intermediate Java/ CSC-112
  4.  * Final part 2, Zip-City gui with database connection
  5.  * Gui program that queries a database for zipcodes of cities/towns
  6.  * dani1996dj@gmail.com
  7.  */
  8. package application;
  9.  
  10. import java.sql.*;
  11.  
  12. public class DBConnection {
  13.  
  14.     // necissary fields for a read only connection to the database
  15.     private static final String DATABASE = "silvestri";
  16.     private static final String USERNAME = "readonly";
  17.     private static final String PASSWORD = "readonly";
  18.  
  19.     static String driver = "com.mysql.jdbc.Driver";
  20.     static String url = "jdbc:mysql://cs.stcc.edu/" + DATABASE + "?user=" + USERNAME + "&password=" + PASSWORD;
  21.  
  22.     Connection conn = null;
  23.     Statement statement;
  24.  
  25.     // Connect to the database
  26.     public void connect() throws Exception {
  27.  
  28.         // creates a connection to the database
  29.         Class.forName(driver).newInstance();
  30.  
  31.         conn = DriverManager.getConnection(url);
  32.  
  33.     }
  34.  
  35.     // Queries the database for the city and state of the zipcode provided by
  36.     // the user
  37.     public String[] getCity_State(int zip) throws SQLException {
  38.  
  39.         statement = conn.createStatement();
  40.         ResultSet res = statement.executeQuery("SELECT city,state FROM Zipcodes WHERE zipcode =" + zip);
  41.  
  42.         String[] strs = new String[2];
  43.  
  44.         while (res.next()) {
  45.             strs[0] = res.getString(1);
  46.             strs[1] = res.getString(2);
  47.         }
  48.         return strs;
  49.     }
  50.  
  51.     // Queries the database for the zip code(s) within he city and state
  52.     // provided by the user
  53.     public String getZips(String city, String state) throws SQLException {
  54.  
  55.         statement = conn.createStatement();
  56.         ResultSet res = statement
  57.                 .executeQuery("SELECT zipcode FROM Zipcodes WHERE city = '" + city + "' AND state = '" + state + "'");
  58.  
  59.         String zipcode = "";
  60.  
  61.         while (res.next()) {
  62.             zipcode += res.getString("zipcode") + "\n";
  63.         }
  64.  
  65.         return zipcode;
  66.     }
  67.  
  68.     // closes the connection to the database, executed at the end of a query
  69.     public void close() throws SQLException {
  70.         conn.close();
  71.     }
  72.  
  73. }
Add Comment
Please, Sign In to add comment