简体   繁体   中英

Cant retrieve column values from mySql database java

I have 2 records in mySql database and I am not able to retrieve 2 values from a column called origin. I am only able to retrieve the value in the first row but not the second. my code is in a method below:

public String[] sequences(){
    String[] origins=new String[2];  


     Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/geneBank";
        String user = "technoGangster";
        String password = "configurationn";

        try {
            con = DriverManager.getConnection(url, user, password);
            st = con.createStatement();
          String query=null;

            query ="SELECT Origin from T1DAlleles";

            rs = st.executeQuery(query);
int rowCount=0;
            if (rs.next()) {

                origins[rowCount]=rs.getString("Origin");
                 rowCount++;
            }
} catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                    }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(Version.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }  
        int i=0;
        for(i=0;i<origins.length;i++){
            JOptionPane.showMessageDialog(null,origins[i]);
        }
    return origins;    

}

代替if,您应该使用while循环,如下所示:

while (rs.next()) {

If you only need the values of this column, change the condition 'if' for the loop 'while'

eg

      while (rs.next()) {

            origins[rowCount]=rs.getString("Origin");
             rowCount++;
        }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM