/*查询数据的jdbc代码*/
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();
}
}
}