如何修复Java中的DB问题(使用DERBY DB)?

时间:2014-01-18 14:04:50

标签: java database derby

 try {
    Class.forName("org.apache.derby.jdbc.ClientDriver");  
    Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/gledi", "root", "root");  

     String sql = "SELECT MAX(NR) from ROOT.GLEDI";

     PreparedStatement   pst = con.prepareStatement(sql);
     ResultSet   rs = pst.executeQuery();

     if (rs.next()) {

         String nr1= rs.getString("MAX(NR)"); // here is the whole problem !!!!! how   can i fix it 
         text.setText(nr1);
     }  

    } catch (Exception e) {
    }

1 个答案:

答案 0 :(得分:3)

给它起个名字然后查找。

该列是字符串类型还是数字?

空的catch块是错误的。打印或记录堆栈跟踪。你永远不会知道是否会抛出异常。

当然你不想要select count(*) from root.gledi?这个查询对我来说不对。

您不应该像Connection一样关闭Statement块中的ResultSetfinallyConnection

您应该将此代码封装在方法中并为其指定import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * JdbcDemo * @author Michael * @link http://stackoverflow.com/questions/21205161/how-to-fix-a-db-probblem-in-java-with-derby-db/21205183#21205183 * @since 1/18/14 9:51 AM */ public class JdbcDemo { private static final String SELECT_MAX_ROW_NUMBER = "SELECT MAX(NR) as maxnr from ROOT.GLEDI"; private Connection connection; public JdbcDemo(Connection connection) { this.connection = connection; } public String getMaxRowNumber() { String maxRowNumber = ""; PreparedStatement ps = null; ResultSet rs = null; try { ps = connection.prepareStatement(SELECT_MAX_ROW_NUMBER); rs = ps.executeQuery(); while (rs.next()) { maxRowNumber = rs.getString("maxnr"); } } catch (Exception e) { e.printStackTrace(); // better to log this. maxRowNumber = ""; } finally { close(rs); close(ps); } return maxRowNumber; } // belongs in a database utility class public static void close(Statement st) { try { if (st != null) { st.close(); } } catch (SQLException e) { e.printStackTrace(); // better to log this } } // belongs in a database utility class public static void close(ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); // better to log this } } } ,而不是每次都创建它。

这么少的代码,很多错误。

以下是我的写作方式:

{{1}}