Hello, I just started with SQL in Java (in fact, I also recently started working with Java). and I created a class to connect to the MySQL database, and it all worked well.
Now I have a question for getting the result.
in PHP I would do something like
While($row = mysql_fetch_assoc()) { echo $row['rowname']; }
In Java, I tried to create something similar to this, but I don’t know if it will go the right way or what it should be completely different or something else .. this is what I did (see getResultList method)
public class MysqlConnect{ private String query; private ResultSet rs; public void connectToAndQueryDatabase(String database, String username, String password) throws SQLException { Connection con = null; try { con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/" + database, username, password); } catch (SQLException e) { e.printStackTrace(); } Statement stmt = con.createStatement(); rs = stmt.executeQuery(query); } public void setQuery(String query) { this.query = query; } public List getResultList() { ArrayList<HashMap> row = new ArrayList<HashMap>(); while(row = rs.next()) { } return rs; } }
source share