问题描述:

I have a quick question. I'm a beginner programmer and for school we need to make a little console code which prints the result of a query in the console. How ever much I tried it didnt work me, all I get is some strange text instead of the query result.

Here's my main class, I also have a second class which is called SimpleDataSourceV2 (this class holds the code for making connection to the mySQL database.

 public static void main(String[] args) {

try {

Connection conn = SimpleDataSourceV2.getConnection();

doQuery(conn);

conn.close();

}

catch ( Exception e){

System.out.print(e);

}

}

public static void doQuery(Connection conn) {

try {

Statement stat = conn.createStatement();

ResultSet result = stat.executeQuery("SELECT * FROM employee");

while (result.next()) {

System.out.println(result);

}

result.close();

stat.close();

}

catch ( SQLException e){

System.out.print(e);

}

}

This are the two methods which I use. The employee table holds different information such as name, adress, city, etc.

Here is what my output is:

run:

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

BUILD SUCCESSFUL (total time: 1 second)

Can anyone please tell me what i'm doing wrong?

Thank you in advance.

网友答案:

If you directly try to print ResultSet, you will get the output like that only. If you know number of columns, then write a loop and print column values

while (result.next()) {
    for (int columnIndex = 1; columnIndex <= numberOfColumns; columnIndex ++){
        System.out.println(columnIndex + "<====>" + result.getString(columnIndex));
    }
}

If you don't know the column count, you can get it using ResultSetMetaData like this

 java.sql.ResultSetMetaData rsmd = result.getMetaData();
 int numberOfColumns = rsmd.getColumnCount();
相关阅读:
Top