I'm trying to search the database using the code in java, but I can not. The database is connected, but the search is not performed. I created two classes, one that owns the class with the connection method, and the other, which is the main one. In it, I call the connection method. I used Deitel's book as a base.
Follow the code:
public class Conexao {
public static Statement conectarBanco() {
final String DATABASE_URL = "jdbc:mysql://localhost/locadora";
final String ROOT = "root";
final String SENHA = "";
try(Connection connection = DriverManager.getConnection(DATABASE_URL, ROOT, SENHA);){
Statement statement = connection.createStatement();
System.out.println("Conectado!");
return statement;
}
catch(SQLException sqlException) {
sqlException.printStackTrace();
}
return null;
}
}
public class Principal {
public static void main(String args[]) throws SQLException {
Statement statement;
int numberOfColumns;
final String SELECT_QUERY = "select*from cliente";
statement = Conexao.conectarBanco();
ResultSet resultSet = statement.executeQuery(SELECT_QUERY);
ResultSetMetaData metaData = (ResultSetMetaData) resultSet.getMetaData();
numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++) {
System.out.println(metaData.getColumnName(i));
}
while(resultSet.next()) {
for(int i = 1; i<= numberOfColumns; i++) {
System.out.println(resultSet.getObject(i));
System.out.println();
}
}
}
}