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 c, int id, String name, String breed, double height,
- String birthDate) {
- try {
- PreparedStatement ps;
- ps = c.prepareStatement("INSERT INTO horse VALUES (?, ?, ?, ?, ?) ");
- int i = 1;
- // first column ISBN is Number So set int instead of String
- ps.setInt(i++, id);
- ps.setString(i++, name);
- ps.setString(i++, breed);
- ps.setDouble(i++, height);
- ps.setString(i++, birthDate);
- int r = ps.executeUpdate();
- System.out.println("Number of inserts : " + r);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public static void selectAllHorses(Connection c) {
- try {
- Statement stmt = c.createStatement();
- String sql = " SELECT * FROM HORSE;";
- System.out.println("All horses: ");
- System.out.println(stmt.executeQuery(sql));
- }
- catch (Exception e) {
- System.exit(0);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment