JAva面接学習ノートの基礎部分
/*クエリーデータのjdbcコード*/
/*追加削除を実行するjdbcコード*/
/*PreparedStatementの使い方*/
public class TestJDBC {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); //
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:sxt", "scott", "tiger");
// ,sxt
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dept");
while (rs.next()) {
int deptno = rs.getInt("deptno"); // int
String dname = rs.getString("dname"); // String
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null; // GC ,
}
if (stmt != null) {
stmt.close();
stmt = null; // GC ,
}
if (conn != null) {
conn.close();
conn = null; // GC ,
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/*追加削除を実行するjdbcコード*/
public static void main(String[] args) {
Statement stmt = null;
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); //
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:sxt", "scott", "tiger");
// ,sxt
stmt = conn.createStatement();
String sql = "insert into dept2 values (98,'game','fuzhou')";
stmt.executeUpdate(sql);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null; // GC ,
}
if (conn != null) {
conn.close();
conn = null; // GC ,
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/*PreparedStatementの使い方*/
public static void main(String[] args) {
PreparedStatement pstmt = null;
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); //
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:sxt", "scott", "tiger");
// ,sxt
String sql = "insert into dept2 values (?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 98); // id
pstmt.setString(2, "game"); //
pstmt.setString(3, "fuzhou"); //
pstmt.executeUpdate(sql);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
pstmt = null; // GC ,
}
if (conn != null) {
conn.close();
conn = null; // GC ,
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}