1\
说明:因为编程经验有限,在一些细节上,难免会有疏漏,特记录在此。
JDBC简介: JDBC 使用说明
2.1\
这是一个 关于人口统计的 关系型数据库:
2.2\
需求:查询 某一年 某个类型 人口的数据
database实现如下:
2.3\
JDBC实现部分:
public Integer getTypeValByYear(String type, String year) {
int ans = 0;
try {
Connection conn = getConn();
// String sql = "select ? from population_stat "+
// "where year = ?";
String sql = "select "+type+" from population_stat "+
"where year = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, year);
rs = pstmt.executeQuery();
while(rs.next()) {
ans=rs.getInt(1);
}
}catch(SQLException e) {
e.printStackTrace();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}finally {
closeAll(conn, pstmt, rs);
}
return ans;
}
//调用
connDb conn=new connDb();
conn.getTypeValByYear(type, year)
3\
问题发生在sql命令注释的那一行,注释是先前失败的写法
总结:
- 如果JDBC发送的sql命令中 包含待确定的value(比如year),用?占位符
- 如果包含已确定的attribute(比如type),用java字符串拼接的方式,嵌入sql命令