import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//stmt.executeUpdate("create table People(name varchar(255),A int,B int)");
//stmt.executeUpdate("insert into People values('张三',1,0)");
//stmt.executeUpdate("insert into People values('李四',2,1)");
//stmt.executeUpdate("insert into People values('王五',3,1)");
//stmt.executeUpdate("insert into People values('赵云',4,2)");
//stmt.executeUpdate("insert into People values('张飞',5,3)");
public class Test {
private static void query(Connection conn,String sql,int a) {
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement(sql);
stmt.setInt(1, a);
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name")+":"+rs.getInt("A"));
query(conn,sql,rs.getInt("A"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
rs=null;
System.out.println(a+":rs closed.");
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
stmt=null;
System.out.println(a+":stmt closed.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
System.out.println("===============================");
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:derby:E:/Derby/test");
String sql="select * from people where B=?";
query(conn,sql, 1);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
System.out.println("Connection关闭。");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}