我想在postgres中显示一个带有“Date”列的表。 我想这与解析字符串到目前为止有关。我尝试使用简单的日期格式,但我没有成功。
我之前实际上发过类似的问题并尝试了给出的建议,但我仍然没有成功。如果有人可以使用下面的代码给我一个样本,我将不胜感激。
我无法解析字符串到日期并显示数据......下面是我的代码。
myDAO
package source;
import java.sql.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
public class parseDAO {
private Database database;
public parseDAO(Database database) {
this.database = database;
}
public List<parseBean> results() throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String querystring = "select * from dateparse";
List<parseBean> result_array = new ArrayList<parseBean>();
try {
connection = database.getConnection();
statement = connection.prepareStatement(querystring);
resultSet = statement.executeQuery();
while (resultSet.next()) {
parseBean resultsarray = new parseBean();
resultsarray.setDate(resultSet.getDate("date"));
resultsarray.setName(resultSet.getString("name"));
resultsarray.setAddress(resultSet.getString("address"));
result_array.add(resultsarray);
}
} finally {
try { resultSet.close(); } catch (SQLException logOrIgnore) {}
try { statement.close(); } catch (SQLException logOrIgnore) {}
try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return result_array;
}
}
myServlet
package source;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class parseServlet extends HttpServlet {
private parseDAO parseDAO;
@Override
public void init() throws ServletException {
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://localhost/myDB";
String username = "postgres";
String password = "secret";
Database database = new Database(driver, url, username, password);
this.parseDAO = new parseDAO(database);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
List<parseBean> result_array = parseDAO.results();
request.setAttribute("result_array", result_array);
request.getRequestDispatcher("results.jsp").forward(request, response);
}
catch (SQLException e) {
throw new ServletException("Cannot retrieve areas", e);
}
}
}
答案 0 :(得分:2)
在parseBean
课程中,更改
private String date;
到
private Date date; // Note: java.util.Date, NOT java.sql.Date!
并更改
resultsarray.setDate(resultSet.getString("date"));
到
resultsarray.setDate(resultSet.getDate("date"));
在JSP中展示时,请使用JSTL <fmt:formatDate>
与指定的pattern:
<fmt:formatDate value="${parseBean.date}" pattern="yyyy-MM-dd" />
无关,也可以使用Java Naming Conventions。类名应以大写字母开头。将parseBean
重命名为ParseBean
。