5.9 LAB - Database programming with Java (SQLite) Complete the Java program to create a Horse table, insert one row, and
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am
5.9 LAB - Database programming with Java (SQLite) Complete the Java program to create a Horse table, insert one row, and
LabProgram.java Load default template... 8 9 1 import java.sql.*; 2 3 public class SQLite JDBC { 4 5 public static void main(String[] args) { 6 //creates connection 7 Connection c = createConnection(); //creates table create Table(C); 10 //inserts a row in table 11 insertHorse(C, 1, "Babe", "Quarter Horse", 15.3, "2015-02-10"); 12 //prints the table 13 selectAllHorses(C); 14 } 15 16 //creates connection to database 17 public static Connection createConnection() { 18 10 //connection object 19 19 Connection c = null; 20 21 21 try { 22 //driver for sqlite jdbc 23 Class. for Name("org.sqlite. JDBC"); 24 //url for the database 25 String url = "jdbc: sqlite::in-memory"; 26 C = Driver Manager.getConnection(url); 27 } catch (Exception e) { 28 System.err.println( e.getClass().getName() + ": " + e.getMessage()); 29 System.exit(0); 30 } 31 32 return c; 33 } 34 35 //creates Horse Table 36 public static void create Table(Connection c) { 37 //sql query for creating table 38 String sql = "CREATE TABLE Horse (\n" 39 ID integer PRIMARY KEY, NOT NULL, \n" 40 40 Name text, \n" 41 Breed text, \n" 42 Height double, \n" 43 BirthDate text, \n" 44 + ");"; 45 46 try { 47 //statement object + 11 + 11 + 11
try { 7/statement object Statement stmt = c.createStatement(); // executing sql query stmt.execute(sql); } catch (Exception e) { System.exit(0); } } //method for inserting a row in the table public static void insertHorse(Connection c, int id, String name, String breed, double height, String b try { //statement object Statement stmt = c.createStatement(); //sql query String sql = String.format("INSERT INTO Horse (ID, Name, Breed, Height, BirthDate) "VALUES (%, %s, %s, %lf, %);", id, name, breed, height, birthdate); + 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 //executing sql query stmt.executeUpdate(sql); } catch (Exception e) { System.exit(0); } } //method for printing the table public static void selectAllHorses(Connection c) { try { //statement object Statement stmt = c.createStatement(); //sql query String sql = "SELECT * FROM Horse;"; //executing sql query System.out.println("All horses: "); System.out.println(stmt.executeQuery( sql)); } catch (Exception e) { System.exit(0); } } 94 }