Advertisement
Guest User

VSA prve cviko

a guest
Feb 13th, 2017
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 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 javaapplication1;
  7. import java.sql.*;
  8. /**
  9. *
  10. * @author xpodluckyf
  11. */
  12. public class JavaApplication1 {
  13. // JDBC driver name and database URL
  14. static final String JDBC_DRIVER = "org.apache.derby.jdbc.ClientDrive";
  15. static final String DB_URL = "jdbc:derby://localhost:1527/sample";
  16.  
  17. // Database credentials
  18. static final String USER = "app";
  19. static final String PASS = "app";
  20.  
  21.  
  22. /**
  23. * @param args the command line arguments
  24. */
  25. public static void main(String[] args) throws ClassNotFoundException, SQLException {
  26. //STEP 3: Open a connection
  27. Statement stmt = null;
  28. Statement stmt1 = null;
  29. Connection conn = null;
  30. try{ Class.forName("org.apache.derby.jdbc.ClientDriver");
  31. System.out.println("Connecting to database...");
  32. conn = DriverManager.getConnection(DB_URL,USER,PASS);
  33.  
  34. //STEP 4: Execute a query
  35. System.out.println("Creating statement...");
  36. stmt = conn.createStatement();
  37. String sql;
  38. sql = "SELECT * FROM KNIHA";
  39. ResultSet rs = stmt.executeQuery(sql);
  40.  
  41. stmt1 = conn.createStatement();
  42. String sql2 = "UPDATE KNIHA set cena=cena*0.9 where cena > 200";
  43. stmt1.executeUpdate(sql2);
  44.  
  45. //STEP 5: Extract data from result set
  46. while(rs.next()){
  47. //Retrieve by column name
  48. String nazov = rs.getString("nazov_knihy");
  49. int cena = rs.getInt("cena");
  50.  
  51. //Display values
  52. System.out.print("Nazov: " + nazov);
  53. System.out.print(", Cena: " + cena);
  54.  
  55. }
  56. System.out.println();
  57. //STEP 6: Clean-up environment
  58. rs.close();
  59. stmt.close();
  60. conn.close();
  61. }catch(SQLException se){
  62. //Handle errors for JDBC
  63. se.printStackTrace();
  64. }catch(Exception e){
  65. //Handle errors for Class.forName
  66. e.printStackTrace();
  67. }finally{
  68. //finally block used to close resources
  69. try{
  70. if(stmt!=null)
  71. stmt.close();
  72. }catch(SQLException se2){
  73. }// nothing we can do
  74. try{
  75. if(conn!=null)
  76. conn.close();
  77. }catch(SQLException se){
  78. se.printStackTrace();
  79. }//end finally try
  80. }//end try
  81. System.out.println("Goodbye!");
  82.  
  83. }
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement