Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- public class LabProgram {
- public static void main (String[] args) {
- Connection c = createConnection();
- createTable(c);
- insertHorse(c, 1, "Babe", "Quarter Horse", 15.3, "2015-02-10");
- selectAllHorses(c);
- }
- public static Connection createConnection() {
- Connection c = null;
- try {
- Class.forName("org.sqlite.JDBC");
- String url = "jdbc:sqlite::in-memory";
- c = DriverManager.getConnection(url);
- }
- catch (Exception e) {
- System.err.println(e.getClass().getName() + ": " + e.getMessage() );
- System.exit(0);
- }
- return c;
- }
- public static void createTable(Connection c) {
- String sql = "CREATE TABLE horse(id INT NOT NULL, "
- + "Name TEXT NULL, Breed TEXT NULL, "
- + "Height DOUBLE NULL, "
- + "BirthDate TEXT NULL, "
- + "PRIMARY KEY ( id ));";
- try {
- Statement statement = c.createStatement();
- statement.execute(sql);
- } catch (Exception e) {
- System.exit(0);
- }
- }
- public static void insertHorse(Connection conn, int id, String name, String breed, double height, String birthDate) {
- String sql = "INSERT INTO Horse VALUES (?, ?, ?, ?, ?)";
- try {
- PreparedStatement pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, id);
- pstmt.setString(2, name);
- pstmt.setString(3, breed);
- pstmt.setDouble(4, height);
- pstmt.setString(5, birthDate);
- pstmt.executeUpdate();
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- }
- // Select and print all rows of Horse table
- // Parameter conn is database connection created in createConnection()
- public static void selectAllHorses(Connection conn) {
- String sql = "SELECT * FROM Horse";
- try {
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- // Loop through the result set
- System.out.print("All horses:");
- while (rs.next()) {
- System.out.println();
- System.out.print("(" + rs.getInt("id") + ", '" +
- rs.getString("Name") + "', '" +
- rs.getString("Breed") + "', " +
- rs.getDouble("Height")+ ", '" +
- rs.getString("BirthDate") + "')" );
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement