One of the variant of the getConnection() method of the DriverManager class accepts url of the database, (String format) a properties file and establishes connection with the database.
Connection con = DriverManager.getConnection(url, properties);
To establish a connection with a database using this method −
Set the Driver class name as a system property −
System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver");
Create a properties object as −
Properties properties = new Properties();
Add the user name and password to the above created Properties object as −
properties.put("user", "root"); properties.put("password", "password");
Finally invoke the getConnection() method of the DriverManager class by passing the URL and, properties object as parameters.
//Getting the connection String url = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(url, properties);
Following JDBC program establishes connection with the MYSQL database using a properties file.
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class EstablishingConnectionUsingProperties { public static void main(String args[]) throws SQLException { //Registering the Driver System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver"); Properties properties = new Properties(); properties.put("user", "root"); properties.put("password", "password"); //Getting the connection String url = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(url, properties); System.out.println("Connection established: "+ con); } }
Connection established: com.mysql.jdbc.JDBC4Connection@2db0f6b2