Pages

Wednesday, November 11, 2009

JDBC Connection through '.properties' File

Hi everyone,
The other day someone was asking me how to establish a JDBC Connection using a '.properties' file. I would like to share it with you. All you need is only a JRE on your machine and a DBMS along with drivers to establish connection, my example includes that of MySQL.
Open Notepad and write the following code with your own port number and password for MySQL and save it as some "jdbc.properties"


jdbc.properties

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:portnumber/databasename

username=root

password=password

Now open other text editor and write the following code and save it as some "JDBCConnection.java". Only thing is that you place the properties file in the same folder as this java file for my example to work, you can as well store it some other place but by giving a fully qualified file name in the statement 

File f=new File("fully qualified name");


JDBCConnection.java


import java.io.*;

import java.util.*;

import java.sql.*;

public class JDBCConnection

{

public static void main(String args[])

{

JDBCConnection j=new JDBCConnection();

j.getConnection();

}

public void getConnection()

{

try

{

File f=new File("./jdbc.properties");

if(f.exists())

{

Properties p=new Properties();

FileInputStream fis=new FileInputStream(f);

p.load(fis);

String driver=p.getProperty("driver");

System.out.println("Driver:"+driver);

String url=p.getProperty("url");

System.out.println("url:"+url);

String username=p.getProperty("username");

System.out.println("Username:"+username);

String password=p.getProperty("password");

System.out.println("Password:"+password);

try

{

Class.forName(driver);

Connection con=DriverManager.getConnection(url,username,password);

System.out.println("JDBC Connection Successfully established");

}

catch (Exception e)

{

e.printStackTrace();

}

}

else

{

System.out.println("No source found!!! Cannot establish JDBC Connection");

}

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

Thanks for going through the content, you can post any queries you have. I will try to solve them at the earliest.