public class Outer {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/data/Sample");
try(con) {
shokai(con);
String sql = "insert into firsttable values (?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1,60);
ps.setString(2,"sixty");
int ret = ps.executeUpdate();
System.out.println("insert count:" + ret);
shokai(con);
}
} catch (SQLException ex ) {
ex.printStackTrace();
}
}
static void shokai(Connection con) {
try {
String sql = "select * from firsttable";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + ":" + name);
}
} catch (SQLException ex ) {
ex.printStackTrace();
}
}
}
10:TEN
20:TWENTY
30:THIRTY
40:xxx
50:fifty
insert count:1
10:TEN
20:TWENTY
30:THIRTY
40:xxx
50:fifty
60:sixty
executeQueryはexecute, getResultSet
exequteUpdateはexecute, getUpdateCount
に置き換えることができる
executeはResultSetをreturnしているかどうかをtrue/falseで返す
public class Outer {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/data/Sample");
try(con) {
shokai(con);
String sql = "insert into firsttable values (?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1,50);
ps.setString(2,"sixty");
boolean bl = ps.execute();
int cnt = ps.getUpdateCount();
System.out.println("insert count:" + cnt);
shokai(con);
}
} catch (SQLException ex ) {
ex.printStackTrace();
}
}
static void shokai(Connection con) {
try {
String sql = "select * from firsttable";
Statement st = con.createStatement();
ResultSet rs = null;
if(st.execute(sql)) rs = st.getResultSet();
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + ":" + name);
}
} catch (SQLException ex ) {
ex.printStackTrace();
}
}
}