如何使用jdbc和sql查询编写条件?

时间:2014-02-26 13:22:18

标签: java mysql sql-server jdbc

在这段代码中,我使用sql查询和JDBC从两个表中获取数据。现在你可以看到查询的结果在rs里面。            我现在想要的是我想检查每个记录(从哪个表来,并根据它写一些HTML并打印所有记录)。            任何人都可以告诉我如何检查其中的每条记录????

例如:

如果第一条记录来自博客表,那么我想打印博客标题并给它一些链接。

如果记录来自问题表,那么我想打印问题和问题的所有答案。

希望你明白了吗?

代码:

Statement stmt=null;
             DBconnection db=new DBconnection();
             Connection con=db.dbConn();
             try{
             stmt = con.createStatement();  


             ResultSet rs = stmt.executeQuery("select description , user ,title , date from(select blog_description as description ,users as user,blog_title as title ,created_date as date from  blog  union select ask_question as description ,users as user ,ask_question as title , created_on as date from askquestions ) as aa order by date desc");

             while(rs.next())
             {

                  System.out.println("this is data regarding sql query==="+rs.getString(2));     

                  retstr+="<table><tr>";
                  retstr+="<td style='width:725px; font-size:14px; font-family:Palatino Linotype; color:#1147a9'>"+rs.getString(2)+"&nbsp;:&nbsp; shared a new Note.</td>";
                  retstr+="</tr></table><br/> ";

                  retstr+="<li style=' font-size:12px;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Title : "+rs.getString(3)+"<span style='font-size:10px; color:#ccc; '>&nbsp;&nbsp;"+rs.getString(4)+"</span></li> <br/> ";  

                  retstr+="<table><tr>";
                  retstr+="<td style='width:30px;'></td><td style='width:725px; color:#1147a9;  border-bottom : 2px dotted #ccc; margin-bottom: 10px; font-size:11px; font-family:Palatino Linotype; margin-bottom:20px;'>Description : "+rs.getString(1)+"<a style='font-size:12px; font family:Palatino Linotype; color:#007fc0; margin-bottom:20px;' href='blogs.jsp'>&nbsp;&nbsp;Read More..</a></td>";               
                  retstr+="</tr></table>";
             }

1 个答案:

答案 0 :(得分:0)

再添加一列,该列将提供每行的源表信息:

SELECT description, USER, title, date from, source
  (SELECT blog_description AS description,
          users AS USER,
          blog_title AS title,
          created_date AS date,
          'blog' as source
   FROM   blog

   UNION 

   SELECT ask_question AS description,
          users AS USER,
          ask_question AS title,
          created_on AS date,
         'askquestions' as source
   FROM askquestions
) AS aa
ORDER BY date DESC