java - 在jsp中显示查询中的非空值

标签 java mysql jsp

在这部分代码中:

try {
connection = DriverManager.getConnection(
connectionUrl + dbName, userId, password);
statement = connection.createStatement();
String sql = "SELECT text_pub, path_photo  FROM publication,publier, consomateur WHERE publication.id_publication=publier.publication_id_publication AND publier.users_id_user=consomateur.code_bar AND consomateur.code_bar = "+idUser+" AND 'path_photo' IS NOT NULL AND 'text_pub' IS NOT NULL";

resultSet = statement.executeQuery(sql);



while (resultSet.next()) {
%>

    <tr bgcolor="#8FBC8F">

<td><%=resultSet.getString("text_pub")%></td>
<img src="images/<%=resultSet.getString("path_photo")%>" width="150" height="130"></td>

<%}
%>

我正在尝试从表中选择两个值,其中一些值可以为空,例如,我的列 text_pub 可以有一个值,而我的列 path_photo 中没有值,反之亦然,所以以防万一我有text_pub,没有path_photo,我只想显示text_pub,但问题是不仅显示了text_pub的值,而且还显示了为空的path_photo的值。 PS:我知道像这样的处理最好在 servlet 中完成,但我真的想让它在 jsp 中工作。谢谢。

最佳答案

向 SQL 查询添加 IFNULL 检查:

SELECT IFNULL(text_pub,DEFAULT("")), IFNULL(path_photo,DEFAULT("")) FROM publication,publier,...

或者添加对 resultSet.getString(..) 返回值的检查

String text = resultSet.getString("text_pub");
if (text==null) {
    text = "";
}

编辑:

in case I have text_pub and don't have path_photo, I want to display only the text_pub this answer doesn't cover this

<%
while (resultSet.next()) {
    String pub = resultSet.getString("text_pub");
    if (pub==null) {
        pub = "";
    }
    String photo = resultSet.getString("path_photo");
%>
    <tr bgcolor="#8FBC8F">
        <td><%= pub %></td>
<%
    if (photo!=null) {
%>
        <td><img src="images/<%=photo%>" width="150" height="130"></td>
<%
    }
}
%>

关于java - 在jsp中显示查询中的非空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22174697/

相关文章:

java - System.in默认指的是什么?

php - 将内爆多重选择更新到数据库中

mysql - 为子查询 MySQL 中的表分配别名

java - 用 PDFBox 中的相同资源替换图像

java - 尝试将 Spring 应用程序制作为 Web MVC

MySql 合并两个查询(subselect or join or union)

java - getParamter() 返回 NULL

jsp - JSP/Servlet 中的倒计时器

java - JSP 表达式语言中的数组文字?

java - 测试 NFE 的 Catch 语句