Reputation: 75
Hi so I'm starting to learn about database connections in JAVA and I'm developing a mini application which requires a database. I wanted to know what's the proper way of using the the Connection object so that I can use it with multiple methods.
A method to Add a new record, another to search for a specific key and so on. I will have to access multiple tables each having their own own class and set of methods.
If there's any good book out there about Software Development in JAVA, that might be useful too.
Upvotes: 2
Views: 2046
Reputation: 2565
if the application is small you can create a connection object each time you hit the database but if the number of request to the database is pretty high you can use Connection pool you can use BasicDataSource which is an apache project use singleton pattern to wrapp the instance of basic dataSource and retrieve the connection Object each time you want from that wrapping class DataWrapper
import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
public class DataWrapper {
private static DataSource datasource;
private static void initialize() throws Exception {
Properties props = new Properties();
props.put("url", "jdbc:mysql://localhost:3306/testbd");
props.put("password", "root");
props.put("username", "root");
props.put("driverClassName", "com.mysql.jdbc.Driver");
props.put("initialSize", "10");
props.put("maxTotal", "15");
props.put("maxIdle", "10");
props.put("minIdle", "5");
datasource = BasicDataSourceFactory.createDataSource(props);
}
public static synchronized Connection getConnection() throws Exception {
if (datasource == null) {
initialize();
}
return datasource.getConnection();
}
}
caller
Connection con=DataWrapper.getConnection();
PreparedStatement statement=con.prepareStatement("select * from users");
ResultSet result= statement.executeQuery();
result.next();
System.out.println(result.getString(1));
//dont forget to close the connection object
con.close();
Upvotes: 0
Reputation: 7565
I think that for simple cases just open and close the connection on each query. For more complicated cases (like a server) you can use connection pool which keeps a list of opened connections
Upvotes: 3