我很难从多个表中检索数据。它将成为一个搜索表单及其关系数据库。如何从Java Servlet中的多个表(PostgreSQL)中检索数据?
问题1:如何从多个表中检索数据?
问题2:同时我面临的另一个问题是,我不能得到任何结果,如果我尝试只能通过名称或姓氏进行搜索。只有当我使用出生日期时才会得到结果。为什么?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.io.PrintWriter out = response.getWriter();
Connection conn = null;{ // while there is no connections, proceed to the next step
try {
Class.forName("org.postgresql.Driver"); // importing the driver to use the getConnection method
conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/caglar", "postgres", //?searchpath=cag
"abracadabra");
System.out.println("Connected to the database"); // console message
String agent_name = request.getParameter("givenname"); // variable - reads from user input
String agent_lastname = request.getParameter("familyname"); // variable - reads from user input
String dob = request.getParameter("birthyear"); // variable - reads from user input
ArrayList al=null;
ArrayList agent_list =new ArrayList();
//Problem 1: If dob is not given, it is not searching by name or lastname.
//String query = "select * from agent where givenname='"+agent_name+"' or familyname='"+agent_lastname+"' or birthyear='"+dob+"' order by givenname";
String query = "select * from agent where givenname='"+agent_name+"' or familyname='"+agent_lastname+"' ";
if(dob!=null && !"".equals(dob)) // if date of birth fiel is left blank, it will still proceed to the results page
query = query + " or birthyear='"+dob+"'"; // if date of birth exists, it will take it into account as well
query = query+ "order by givenname"; // ordering by first name
System.out.println("query" + query); // console message
Statement st = conn.createStatement(); // connection statement
ResultSet rs = st.executeQuery(query); // executing our query
while(rs.next())
{
al = new ArrayList();
al.add(rs.getString(1));//id
al.add(rs.getString(2));//dob
al.add(rs.getString(3));//name
al.add(rs.getString(4));//lastname
System.out.println("al :: "+al);
agent_list.add(al);
}
request.setAttribute("agentList",agent_list);
哇,这段代码极易受SQL注入攻击。想象一下,如果某人提交给定名称(不含双引号)“myname”; DROP TABLE agent; - “会发生什么情况。您至少需要使用参数化查询。 – 2012-04-24 03:11:36
虽然不是直接的答案,但我强烈建议您查看(a)Facelets/JSF2和(b)JPA2。无论如何,请显示您正在从工作和非工作测试用例生成的查询文本。 – 2012-04-24 03:14:13
据推测,如果DoB没有被给出,它不会匹配任何东西。这意味着您的给定名称/姓氏WHERE子句总是评估为false。没有数据,为什么很难说。这可能是大小写敏感,引用或各种各样的事情。 – 2012-04-24 03:17:09