Acceso a datos JDBC

import java.math.BigDecimal;
import java.sql.*;


public class Derby {

 public static void main(String[] args) {

 try (Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/JavaTunesDB", "guest",
 "password");) {
 // rest of code

 String sql = "SELECT ITEM_ID, Title, Price FROM ITEM";

 // conn is connection as from previous slide
 // create a Statement object
 Statement stmt = conn.createStatement();
 // execute the SQL with it
 ResultSet rs = stmt.executeQuery(sql);
 while (rs.next()) {
 long id = rs.getLong("ITEM_ID");
 String title = rs.getString("Title");
 BigDecimal price = rs.getBigDecimal("Price");
 System.out.println(id + "," + title + "," + price);
 } // Do something with data (not shown)
 
 
 sql = "SELECT Title, Price FROM ITEM " +
 "WHERE ITEM_ID = ?";
 
 PreparedStatement pstmt = conn.prepareStatement(sql);
 // set the ? - they are numbered starting at 1
 pstmt.setInt(1, 10);
 // execute the PreparedStatement and get a ResultSet
 rs = pstmt.executeQuery();
 
 rs.next();
 String title = rs.getString("Title");
 Double price = rs.getDouble("Price");
 System.out.println(title + "," + price);
 
 
 } catch (SQLException sqle) {
 System.out.println(sqle.getMessage());
 }
 }

}

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos