如果以下代码有效,'rs'的价值是多少?

时间:2014-04-19 03:47:50

标签: mysql jdbc

preparedStatement = connect.prepareStatement("select * from mark where clsnum='"+t1.getText()+"'");
rs = preparedStatement.executeQuery(); // ResultSet

假设上述SQL查询有效,即找到与搜索到的'clsnum'对应的值。那么'rs'的价值是什么?

1 个答案:

答案 0 :(得分:2)

  

假设我需要根据'rs'中的值显示消息。如果'rs'包含一行,则需要显示消息'Number Found'。如果'rs'不包含任何值,我需要显示消息'Number Not Found'。那我该怎么办?

示例1

SELECT COUNT( clsnum ) AS match_count FROM MARK WHERE clsnum ?

如果match_count0更重要,则显示消息'Number Found'其他'Number Not Found'

示例2

SELECT COUNT( clsnum ) > 0 AS match_found FROM MARK WHERE clsnum ?

如果match_foundtrue,则显示消息'Number Found'其他'Number Not Found'

示例3

SELECT IF( COUNT( clsnum ) > 0,
           'Number Found', 
           'Number Not Found' 
       ) AS message_to_display
FROM MARK 
WHERE clsnum ?

如果您的要求只是显示消息,请从message_to_display阅读ResultSet并显示。

而且,你没有使用准备好的声明。使用占位符作为输入值,并使用相关的setXXX方法绑定它们。

示例4

String query = "
    SELECT IF( COUNT( clsnum ) > 0,
               'Number Found', 
               'Number Not Found' 
           ) AS message_to_display
    FROM MARK 
    WHERE clsnum ?";

PreparedStatement pst = connect.prepareStatement( query );
pst.setString( 1, t1.getText() );

ResultSet rs = preparedStatement.executeQuery();
String messageToDisplay = "Number Not Found";
if( rs.next() ) {
  messageToDisplay  = rs.getString( message_to_display );
}
// procedure further with your other operations