Guest User

Untitled

a guest
Jan 13th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1.  
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.sql.Date;
  9.  
  10.  
  11. public class JdbcTest {
  12.  
  13. /**
  14. * @param args
  15. * @throws Exception
  16. */
  17. public static void main(String[] args) {
  18.  
  19. try {
  20. Class.forName("org.apache.derby.jdbc.ClientDriver");
  21. } catch(ClassNotFoundException e) {
  22. System.out.println("Please ensure that the Derby Client jar is in your classpath");
  23. System.exit(0);
  24. }
  25.  
  26. String URL = "jdbc:derby://localhost:1527/JavaTunesDB";
  27. //String URL = "jdbc:derby://192.168.1.149:1527/JavaTunesDB";
  28. try {
  29. Connection conn = DriverManager.getConnection(URL, "guest", "password");
  30. create(conn);
  31. update(conn);
  32. retrieve(conn);
  33.  
  34.  
  35. }catch(SQLException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39.  
  40. public static void update(Connection conn) throws SQLException {
  41. String sql = "UPDATE ITEM SET ARTIST=? WHERE ARTIST=?";
  42. PreparedStatement stmt = conn.prepareStatement(sql);
  43. stmt.setString(1, "Xeander Lennox");
  44. stmt.setString(2, "Anthony Lennox");
  45.  
  46. int count = stmt.executeUpdate();
  47. if (count==1){
  48. System.out.println("Record updated");
  49. } else {
  50. System.out.println("No records were updated");
  51. }
  52. }
  53.  
  54.  
  55. public static void create(Connection conn) throws SQLException {
  56. String sql = "INSERT INTO ITEM (TITLE, ARTIST, RELEASEDATE, LISTPRICE, PRICE) VALUES (?, ?, ?, ?, ?)";
  57. PreparedStatement stmt = conn.prepareStatement(sql);
  58. stmt.setString(1, "Diva 2");
  59. stmt.setString(2, "Anthony Lennox");
  60. stmt.setDate(3, new Date(System.currentTimeMillis()));
  61. stmt.setDouble(4, 12.99);
  62. stmt.setFloat(5, 10.99f);
  63.  
  64. int count = stmt.executeUpdate();
  65. if (count==1){
  66. System.out.println("Record saved");
  67. } else {
  68. System.out.println("Save failed");
  69. }
  70. }
  71.  
  72. public static void retrieve(Connection conn) throws SQLException {
  73. String sql = "SELECT * FROM ITEM";
  74. Statement stmt = conn.createStatement();
  75. ResultSet rs = stmt.executeQuery(sql);
  76.  
  77. while(rs.next()){
  78. String ID = rs.getString("ITEM_ID");
  79. String Artist = rs.getString("ARTIST");
  80. System.out.println("ID: " + ID + " " + "ARTIST: " + Artist);
  81. }
  82. }
  83.  
  84. }
Add Comment
Please, Sign In to add comment