MutahirA_

Untitled

Nov 13th, 2022
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. import java.sql.*;
  2.  
  3. public class LabProgram {
  4.  
  5. public static void main (String[] args) {
  6. Connection c = createConnection();
  7.  
  8. createTable(c);
  9.  
  10. insertHorse(c, 1, "Babe", "Quarter Horse", 15.3, "2015-02-10");
  11.  
  12. selectAllHorses(c);
  13. }
  14.  
  15. public static Connection createConnection() {
  16. Connection c = null;
  17.  
  18. try {
  19. Class.forName("org.sqlite.JDBC");
  20. String url = "jdbc:sqlite::in-memory";
  21. c = DriverManager.getConnection(url);
  22. }
  23. catch (Exception e) {
  24. System.err.println(e.getClass().getName() + ": " + e.getMessage() );
  25. System.exit(0);
  26. }
  27.  
  28. return c;
  29. }
  30.  
  31. public static void createTable(Connection c) {
  32.  
  33. String sql = "CREATE TABLE horse(id INT NOT NULL, "
  34. + "Name TEXT NULL, Breed TEXT NULL, "
  35. + "Height DOUBLE NULL, "
  36. + "BirthDate TEXT NULL, "
  37. + "PRIMARY KEY ( id ));";
  38. try {
  39. Statement statement = c.createStatement();
  40. statement.execute(sql);
  41.  
  42. } catch (Exception e) {
  43. System.exit(0);
  44. }
  45. }
  46.  
  47. public static void insertHorse(Connection c, int id, String name, String breed, double height,
  48. String birthDate) {
  49.  
  50. try {
  51. PreparedStatement ps;
  52. ps = c.prepareStatement("INSERT INTO horse VALUES (?, ?, ?, ?, ?) ");
  53. int i = 1;
  54. // first column ISBN is Number So set int instead of String
  55. ps.setInt(i++, id);
  56. ps.setString(i++, name);
  57. ps.setString(i++, breed);
  58. ps.setDouble(i++, height);
  59. ps.setString(i++, birthDate);
  60. int r = ps.executeUpdate();
  61. System.out.println("Number of inserts : " + r);
  62. } catch (SQLException e) {
  63. e.printStackTrace();
  64. }
  65.  
  66. }
  67.  
  68. public static void selectAllHorses(Connection c) {
  69. try {
  70. Statement stmt = c.createStatement();
  71. String sql = " SELECT * FROM HORSE;";
  72.  
  73. System.out.println("All horses: ");
  74. System.out.println(stmt.executeQuery(sql));
  75. }
  76. catch (Exception e) {
  77. System.exit(0);
  78. }
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment