Advertisement
Guest User

Untitled

a guest
Apr 24th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 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 main;
  7.  
  8. import java.sql.Connection;
  9. import java.sql.DriverManager;
  10. import java.sql.PreparedStatement;
  11. import java.sql.ResultSet;
  12. import java.sql.SQLException;
  13. import java.sql.Statement;
  14. import java.util.logging.Level;
  15. import java.util.logging.Logger;
  16.  
  17. /**
  18. *
  19. * @author FON
  20. */
  21.  
  22.  
  23.  
  24. public class Main {
  25. private static String url = "jdbc:oracle:thin:@localhost:1521:orcl";
  26. private static String username = "student";
  27. private static String password ="student";
  28.  
  29. public static void main(String[] args) {
  30. System.out.println("Pre unosa: ");
  31. nadjiSvaOdeljenja();
  32. dodajOdeljenje(959, "LABIS", "Beograd");
  33. System.out.println("Posle unosa: ");
  34. nadjiSvaOdeljenja();
  35. }
  36.  
  37. public static void nadjiSvaOdeljenja(){
  38. String query = "SELECT * FROM odeljenje";
  39.  
  40. try (Connection connection = DriverManager.getConnection(url,username ,password );
  41. Statement stmt = connection.createStatement();
  42. ResultSet rs = stmt.executeQuery(query);) {
  43.  
  44. while(rs.next()){
  45. int sifraOdeljenja = rs.getInt("sifraodelj");
  46. String nazivOdeljenja = rs.getString(2);
  47. String grad = rs.getString("grad");
  48.  
  49. System.out.println("Sifra: " + sifraOdeljenja + ", Naziv: " + nazivOdeljenja + ", Grad: "+ grad);
  50. }
  51. //rs.close();
  52. //stmt.close();
  53. //connection.close();
  54.  
  55. } catch (SQLException ex) {
  56. Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
  57. }
  58. }
  59.  
  60. public static void dodajOdeljenje(int sifraOdeljenja, String nazivOdeljenja, String grad){
  61. try {
  62. String query = "INSERT INTO odeljenje VALUES (?,?,?)";
  63. Connection connection = DriverManager.getConnection(url, username, password);
  64. connection.setAutoCommit(false);
  65. PreparedStatement ps = connection.prepareStatement(query);
  66. ps.setInt(1, sifraOdeljenja);
  67. ps.setString(2, nazivOdeljenja);
  68. ps.setString(3, grad);
  69. int number = ps.executeUpdate();
  70.  
  71. if(number == 1){
  72. connection.commit();
  73. }else{
  74. connection.rollback();
  75. }
  76.  
  77. ps.close();
  78. connection.close();
  79. } catch (SQLException ex) {
  80. Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
  81. }
  82. }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement