Use of Resultset, converting String to Array

Asked

Viewed 739 times

0

I’m trying to convert some data that comes from BD to an Array, using Resultset to select BD data. In the code below it does not give any error however If I try to use a:

System.out.println(x[0]);

It does not show the first given, so it seems that the conversion has not been made, I wanted to know if this is how it converts, or if it cannot be done inside the while.

public static void main(String[] args) {

    connection = new Conexao().getConnection();
    String sql = "SELECT * FROM figura";
    try {
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();

        while(rs.next()){
            String x = rs.getString(2);
            String y = rs.getString(3);
            x.toCharArray();
            y.toCharArray();
            System.out.println(x);
        }

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

1 answer

0


You’re looking to ride a Array with 2 values, or 2 Array with 1 value each? Depending on the case, you can create a model and create a ArrayList of your kind.

You are using toCharArray(), then you want an array of char with the String captured from the database? If not, you do not need to use this function. As for the code, you have tried something like this?

public static void main(String[] args) {
    connection = new Conexao().getConnection();
    String sql = "SELECT * FROM figura";
    List<String> x = new ArrayList<String>();
    List<String> y = new ArrayList<String>();

    try {
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();

        while ( rs.next() ) {
            x.add( rs.getString(2) );
            y.add( rs.getString(3) );
        }

        for (String value : x) {
            System.out.println(x);
        }
        for (String value : y) {
            System.out.println(y);
        }

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
  • There are 2 arrays even, the way you showed passed the right value to the array, I’m using mvc same, this was just to test, in case I tried to do in the model the List<String> x e y, I just didn’t understand what I call it inside the while.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.