294761325
2017-04-15 14:45
public class servletList extends HttpServlet {
private static final String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //数据库驱动
//连接数据库的URL地址
private static final String url="jdbc:sqlserver://localhost:1433;DatabaseName=message";
private static final String username="sa";//数据库的用户名
private static final String password="123";//数据库的密码
private static Connection conn=null;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
String sql = "select id,command,description,contents from messageTable";
PreparedStatement statement = conn.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
List<messageItems> messageList = new ArrayList<messageItems>();
while(rs.next())
{
messageItems items = new messageItems();
messageList.add(items);
items.setId(rs.getInt("id"));
items.setCommand(rs.getString("command"));
items.setDescription(rs.getString("description"));
items.setContents(rs.getString("contents"));
}
req.setAttribute("messageList", messageList);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
}
劝你分层写吧,这样更能容易找到问题所在。(说实话你把数据库链接写在servlet中我也是挺醉的,servlet累死了啊!耦合度太高)
这页代码没问题啊
while(rs.next())
{
messageItems items = new messageItems();
messageList.add(items);//此句应移到while的最后
items.setId(rs.getInt("id"));
items.setCommand(rs.getString("command"));
items.setDescription(rs.getString("description"));
items.setContents(rs.getString("contents"));
}
通过自动回复机器人学Mybatis---基础版
107410 学习 · 786 问题
相似问题