JDBC selecting the Max value from an Access table

无人久伴 提交于 2019-12-04 05:40:15

问题


I got error "Column not found" any time i run the following code even though the column exist in my table. Am using access database, Appealing for help please

public class Trial1 {
public static void main (String[]args){

            try{
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
                String url = "jdbc:odbc:SENSOR";
                String user = "";
                String pass = "";
                Connection con = DriverManager.getConnection(url,user,pass);
                Statement stmt  = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);                          //stmt代表資料庫連接成功


                ResultSet rs = stmt.executeQuery("select MAX(LevelNum) from NList");
                 if (rs.next()){

                    int w = rs.getInt("LevelNum");
                   int x= 3;                             

                double i = Math.pow(2, (w-x))-1;
                System.out.printf("i is  %f",i);}


                stmt.close();
                con.close();

            }catch(Exception e)
            {
                System.out.println("Error" + e);
            }

}

}

回答1:


Assuming the error is when you get the result rather than when you execute the query, you probably need something like this instead

// ...
ResultSet rs = stmt.executeQuery("select MAX(LevelNum) as maxLevel from NList");
if (rs.next())
{
    int w = rs.getInt("maxLevel");

    // ... etc.
}



回答2:


Try this...

class Trial1 {
public static void main (String[]args){

            try{
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
                String url = "jdbc:odbc:SENSOR";
                String user = "";
                String pass = "";
                Connection con = DriverManager.getConnection(url,user,pass);
                Statement stmt  = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);                          


                ResultSet rs = stmt.executeQuery("select MAX(LevelNum) as LEVELNUM from NList");
                 if (rs.next()){

                    int w = rs.getInt("LEVELNUM");
                   int x= 3;                             

                double i = Math.pow(2, (w-x))-1;
                System.out.printf("i is  %f",i);}


                stmt.close();
                con.close();

            }catch(Exception e)
            {
                System.out.println("Error" + e);
            }

}


来源:https://stackoverflow.com/questions/16382951/jdbc-selecting-the-max-value-from-an-access-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!