I am working with a JDBC, How do I actually pass my Connection code to other objects?? so that it wouldn’t be so much of a hassle to keep on coding it and do I need other objects to create if I need to close a database connection?? Here’s my code
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import javax.sql.DataSource;
public class DisplayUsers {
ResultSet resultSet = null;
Statement statement = null;
Scanner input = new Scanner(System.in);
DataSource ds = null;
public void showAll() {
System.out.println("Search User: ");
String user = input.nextLine();
String query = "Select * from user";
try {
resultSet = statement.executeQuery(query);
ResultSetMetaData metadata = resultSet.getMetaData();
int columns = metadata.getColumnCount();
while(resultSet.next()){
for(int i = 1 ; i<=columns;i++){
System.out.printf("%-8s\t",resultSet.getObject(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here’s my Connector code
import java.sql.*;
public class Jdbc {
public void dbConn(){
final String url = "jdbc:mysql://localhost:3306/payroll";
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,"root","123192");
}catch(Exception e){
e.printStackTrace();
}
}
}
The best way is to use connection pool. If you are coding Java EE application, you can make the pool in configuration (In glassfish you can use admin console). Server will bind this pool (via DataSource) to a JNDI name you specified (say “jndi/mydb”).
So getting a connection in code is very simple:
You can pass this DataSource everywhere and getConnection as simple as ds.getConnection(), never closing it (because it’s pooled and reused).
P.S. Use of DriverManager as a way of getting connection is appropriate in small console application with no requirements to performance and scalability.