
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Establish Connection with Database Using Properties File in JDBC
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.
Example
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); } }
Output
Connection established: com.mysql.jdbc.JDBC4Connection@2db0f6b2
Advertisements