【问题标题】:How to fix a DB probblem in Java (with DERBY DB)?如何修复 Java 中的数据库问题(使用 DERBY DB)?
【发布时间】:2014-01-18 14:04:49
【问题描述】:
 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) {
    }

【问题讨论】:

  • 告诉我们这条线发生了什么。
  • String nr1 = rs.getString(1);

标签: java database derby


【解决方案1】:

给它起个名字然后查一下。

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

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

确定不想要select count(*) from root.gledi?这个查询在我看来是错误的。

您不应该在 finally 块中关闭 ConnectionStatementResultSet

您应该将此代码封装在一个方法中并给它一个Connection,而不是每次都创建它。

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

我可以这样写:

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
        }
    }
}

【讨论】:

    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 2019-09-26
    • 2014-10-02
    • 2023-04-01
    相关资源
    最近更新 更多