我正在尝试使用这些功能访问数据库。我已经测试了查询并且它可以工作,但我有两个问题:1)我的PostgreSQL数据库中有Timestamp中带有区域类型的数据,当我尝试在java中打印时,它打印例如
01.01.1970 13.35
而不是db中写的值。
2)当我使用servlet打印出url时,它会打印数据库中的第一个值,重复它应该打印的行数,而在DAO类中,它会输出正确的url值。
例如在DAO中它打印:
http://seesaa.net/cubilia.jpg01.01.1970 13.35
http://seesaa.net/cubilia.jpg01.01.1970 14.07
https://msn.com/sit/amet/consectetuer/adipiscing/elit.aspx01.01.1970 14.10
http://examiner.com/ultrices/posuere/cubilia/curae/donec/pharetra.png01.01.1970 14.27
https://google.co.uk/est/donec/odio/justo/sollicitudin/ut/suscipit.js01.01.1970 14.30
http://seesaa.net/cubilia.jpg01.01.1970 14.32
https://dyndns.org/nulla/justo.js01.01.1970 14.46
http://seesaa.net/cubilia.jpg01.01.1970 15.04
在servlet中:
http://seesaa.net/cubilia.jpg
http://seesaa.net/cubilia.jpg
http://seesaa.net/cubilia.jpg
http://seesaa.net/cubilia.jpg
http://seesaa.net/cubilia.jpg
http://seesaa.net/cubilia.jpg
http://seesaa.net/cubilia.jpg
http://seesaa.net/cubilia.jpg
这是DAO类:
public static ArrayList<SessioneLettura> cronologiaPagine(int id) {
DBManager dbmanager = new DBManager();
Connection conn = dbmanager.getConnection();
PreparedStatement pstmt;
Pagina pagina= new Pagina();
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH.mm");
ArrayList<SessioneLettura> sessionelettura = new ArrayList<SessioneLettura>();
try {
pstmt = conn.prepareStatement(
"SELECT sessionelettura.url as url, sessionelettura.data as data FROM sessionelettura INNER JOIN sessione ON codice= sessionelettura.sessione WHERE sessione.utente=?");
pstmt.setInt(1, id);
ResultSet p = pstmt.executeQuery();
while (p.next()) {
pagina.setUrl(p.getString("url"));
SessioneLettura s = new SessioneLettura((sdf.format(p.getTimestamp("data"))),pagina);
System.out.println(s.getPagina().getUrl() + "" + s.getDataletta());
sessionelettura.add(s);
}
conn.commit();
pstmt.close();
conn.close();
} catch (
SQLException e) {
e.printStackTrace();
}
return sessionelettura;
}
这是servlet:
private void cronologia(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("idUtente"));
for (SessioneLettura sa : DataAccess.cronologiaPagine(id)) {
String url = sa.getPagina().getUrl();
System.out.println(url);
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Cronologia.jsp?&idUtente="+id);
request.setAttribute("cronologia", DataAccess.cronologiaPagine(id));
dispatcher.forward(request, response);
}
它根据您的代码正确执行。你写了:
SessioneLettura s =
new SessioneLettura((sdf.format(p.getTimestamp("data"))),pagina);
在这一行中,你写了p.getTimestamp("data")
。您正在调用JDBC驱动程序以将TIMESTAMP WITH TIME ZONE
列检索到java.sql.Timestamp
。 JDBC驱动程序自动将值转换为当前JVM的时区。
然后,您使用dd.MM.yyyy HH.mm
格式打印它。如果想要查看检索到的值的时区,请将z
添加到格式中,如dd.MM.yyyy HH.mm z
中所示。