首先我们需要先建立好数据库,将一些数据插入进去
需要两张表:
province:省份表
city: 城市表
如图:
然后再在java中建立相关的实体类与之对应
再然后,我们就能开始做jdbc的操作了
try {
InputStream in = ConnectionFactory.class.getResourceAsStream("./jdbc.properties");
prop.load(in);
driver = prop.getProperty("jdbc.driver");
url = prop.getProperty("jdbc.url");
user = prop.getProperty("jdbc.user");
password = prop.getProperty("jdbc.password");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
- 获取连接对象
- @return
*/
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
} catch (Exception e) {
throw new RuntimeException(e);
}
return conn;
}
/**
- 关闭资源
- @param conn
- @param pstmt
- @param stmt
- @param rs
*/
public static void close(Connection conn,PreparedStatement pstmt,Statement stmt,ResultSet rs){
try {
if (conn != null) {
conn.close();
}
if (pstmt != null) {
pstmt.close();
}
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
} catch (sqlException e) {
throw new RuntimeException(e);
}
}
首先我们可以在页面加载的时候获取所有省份的信息,sql语句如下
public ArrayList
ResultSet rs = null;
ArrayList
try {
String sql = "select id,place from province";
conn = ConnectionFactory.getConnection();
pstmt = conn.prepareStatement(sql);
pros = new ArrayList
rs = pstmt.executeQuery();
while(rs.next()){
Province province = new Province();
province.setId(rs.getInt(1));
province.setPlace(rs.getString(2));
pros.add(province);
}
} catch (sqlException e) {
throw new RuntimeException(e);
}
return pros;
}
将查到的数据放到后台,建立一个SelectedServlet类,用于接收查询到的所有省份的信息
在这里会用到集合转换Json对象,我们需要导入以下几个包
城市:<select id="city">