Advertisement
Guest User

Untitled

a guest
Mar 7th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package sql;
  7. import java.sql.*;
  8. import java.util.Scanner;
  9. import java.util.logging.*;
  10.  
  11. // java -cp postgresql-9.4-1201.jdbc4.jar:. DBtest
  12.  
  13. public class SQL {
  14.  
  15. public static void main(String[] args) throws SQLException {
  16. String url = "jdbc:postgresql://localhost:5432/postgres";
  17. String user = "postgres";
  18. String password = "Rasmussen123";
  19. Connection con = null;
  20.  
  21.  
  22. //CONNECTING
  23. try {
  24. con = DriverManager.getConnection(url, user, password);
  25.  
  26. } catch (SQLException ex) {
  27. Logger lgr = Logger.getLogger(SQL.class.getName());
  28. lgr.log(Level.WARNING, ex.getMessage(), ex);
  29.  
  30. }
  31.  
  32. task1(con);
  33. }
  34.  
  35. public static void task1(Connection con) throws SQLException{
  36. //RUN AN EXAMPLE QUERY
  37. int userPrice = 0;
  38.  
  39. String tempModel;
  40. float tempSpeed;
  41. int tempPrice;
  42. int priceOfClosest = 0;
  43. String modelOfClosest = "";
  44. float speedOfClosest = 0;
  45. Scanner scanner = new Scanner(System.in);
  46. System.out.println("Giv Price plz");
  47. userPrice = scanner.nextInt();
  48.  
  49. try {
  50. Statement st = con.createStatement();
  51. String query = "SELECT model, price, speed FROM pc";
  52. ResultSet pcs = st.executeQuery(query);
  53. while (pcs.next()) {
  54. tempModel = pcs.getString(1);
  55. tempPrice = pcs.getInt(2);
  56. tempSpeed = pcs.getFloat(3);
  57.  
  58. if(userPrice - tempPrice < tempPrice - priceOfClosest){
  59. modelOfClosest = tempModel;
  60. priceOfClosest = tempPrice;
  61. speedOfClosest = tempSpeed;
  62. }
  63. }
  64. System.out.println(modelOfClosest);
  65. } catch (SQLException e) {
  66. e.printStackTrace();
  67. con.close();
  68. }
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement