Advertisement
MutahirA_

Untitled

Nov 13th, 2022
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 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 conn, int id, String name, String breed, double height, String birthDate) {
  48. String sql = "INSERT INTO Horse VALUES (?, ?, ?, ?, ?)";
  49. try {
  50. PreparedStatement pstmt = conn.prepareStatement(sql);
  51. pstmt.setInt(1, id);
  52. pstmt.setString(2, name);
  53. pstmt.setString(3, breed);
  54. pstmt.setDouble(4, height);
  55. pstmt.setString(5, birthDate);
  56. pstmt.executeUpdate();
  57. } catch (SQLException e) {
  58. System.out.println(e.getMessage());
  59. }
  60. }
  61.  
  62. // Select and print all rows of Horse table
  63. // Parameter conn is database connection created in createConnection()
  64. public static void selectAllHorses(Connection conn) {
  65. String sql = "SELECT * FROM Horse";
  66. try {
  67. Statement stmt = conn.createStatement();
  68. ResultSet rs = stmt.executeQuery(sql);
  69.  
  70. // Loop through the result set
  71. System.out.print("All horses:");
  72. while (rs.next()) {
  73. System.out.println();
  74. System.out.print("(" + rs.getInt("id") + ", '" +
  75. rs.getString("Name") + "', '" +
  76. rs.getString("Breed") + "', " +
  77. rs.getDouble("Height")+ ", '" +
  78. rs.getString("BirthDate") + "')" );
  79. }
  80. } catch (SQLException e) {
  81. System.out.println(e.getMessage());
  82. }
  83. }
  84.  
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement