I have a function that returns the result of a query. The input arguments are the SQL statement and the field to be retrieved, while the output is the result of the query. As expected, the database contains multiple data types. Is there a generic return type I can specify the function to have?
The code below retrieves string…I need to change this to return Integer types as well, preferably, without writing another function.
public static String dbConnect(String sql,String field) throws SQLException, ClassNotFoundException {
Statement stmt;
String DB_URL;
Class.forName("com.mysql.jdbc.Driver");
DB_URL="jdbc:mysql://connectionURL.net:3306/db?autoReconnect=true";
Connection conn =DriverManager.getConnection(DB_URL,DB_USER, DB_PWD);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
String result=null;
while(rs.next()){
result = rs.getString(field);
}
rs.close();
stmt.close();
conn.close();
return result;
}
The might be a better way to do this, but you can always have your function return an
Object– which will then have to be cast into whatever you actually expect to get.But if you do that, perhaps having multiple methods for the various data types you expect might be easier.
(As an aside, reconnecting to the database for every query you run seems like a bad idea.)