Software >> Development >> Languages >> Java >> Examples >> How to retrieve a table from MySQL

import java.lang.String; import java.lang.Object; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.ResultSet; public class ConnMysql { public static void main(String args[]) { Connection conn = null; ResultSet rs = null; try { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://localhost /mysql?user=root&password=root"); } catch(ClassNotFoundException e) { System.err.println("ClassNotFoundException: " e.getMessage()); } catch(InstantiationException e) { System.err.println("InstantiationException: " e.getMessage()); } catch(IllegalAccessException e) { System.err.println("IllegalAccessException: " e.getMessage()); } System.out.println("Display all results:"); rs = conn.createStatement().executeQuery("select * from user"); int columns = rs.getMetaData().getColumnCount(); while(rs.next()) { for (int i=1; i<= columns; i ) { String columnName = rs.getMetaData().getColumnName(i); String columnValue = rs.getString(i); System.out.println(columnName " = " columnValue); System.out.println(); } } } catch(SQLException e) { System.err.println("SQLException: " e.getMessage()); System.err.println("SQLState: " e.getSQLState()); System.err.println("VendorError: " e.getErrorCode()); } finally { try { if(conn != null) conn.close(); } catch(SQLException e) {} } } }