Home > OS >  Is there a way to simply query an existing database without creating entities Spring boot
Is there a way to simply query an existing database without creating entities Spring boot

Time:10-07

I'm not a java developer, i have been developping in other languages and just wondering whether i can just query an existing database from a java app without using an entity that has to be hydrated... I have checked different implementations and JPA or Data jdbc in spring boot all have to be mapped vs en Entity class. I have a database that i want to query and use the data from there to generate some files... but i don't want to map all these tables to an Entity class in java...

I could do this with Pyhto, Php, C etc...

But Java always seems to be very verbose from that perspective...

CodePudding user response:

You can query the database using SQL Syntax, and JDBC. Though beware of SQL Injections :)

See the below example which showcases how to:

try
    {
      // create our mysql database connection
      String myDriver = "org.gjt.mm.mysql.Driver";
      String myUrl = "jdbc:mysql://localhost/test";
      Class.forName(myDriver);
      Connection conn = DriverManager.getConnection(myUrl, "root", "");
      
      String query = "SELECT * FROM users";

      // create the java statement
      Statement st = conn.createStatement();
      
      // execute the query, and get a java resultset
      ResultSet rs = st.executeQuery(query);
      
      // iterate through the java resultset
      while (rs.next())
      {
        int id = rs.getInt("id");
        String firstName = rs.getString("first_name");
        String lastName = rs.getString("last_name");
        Date dateCreated = rs.getDate("date_created");
        boolean isAdmin = rs.getBoolean("is_admin");
        int numPoints = rs.getInt("num_points");
        
        // print the results
        System.out.format("%s, %s, %s, %s, %s, %s\n", id, firstName, lastName, dateCreated, isAdmin, numPoints);
      }
      st.close();
    }
    catch (Exception e)
    {
      System.err.println(e.getMessage());
    }
  }
}

Reference: https://alvinalexander.com/java/java-mysql-select-query-example/

Mysql Connector Reference: https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-connect-drivermanager.html

https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-overview.html

CodePudding user response:

That depends of the meaning of your question. Java is strongly typed language. Of course you can query any database with jdbc and spring boot. However if you want to return the result of your query, you need to create a pojo for it.

  • Related