1
I’m trying to run a database search using java code, but I can’t. The database is connected, but the search is not performed. I created two classes, one that has the class with the connection method, and the other, which is the main one. I call it the connection method. I used as a basis the book of the author Deitel.
Follows 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();
}
}
}
}
Good evening, Gustavo. Thank you so much for the comment. I identified my mistake. I re-read the method and it’s similar to the way you explained it to me. Thank you very much.
– Alexandre Santos da Cruz