Friday 4 April 2014

How to connect to Oracle using JDBC thin client



This is a java program to connect to oracle database connection string and sql query  is customize you have to set your own value. after you compile this code run in the command line with following syntax you can ignore lpad and rpad function it is only given to print data in well tabbed format.





java -cp "path\jdbcjarfilename" classfilename 

I am giving the ojdbc5.jar link here : ojdbc5.jar

import java.sql.*;
import java.io.*;
class OracleCon
{

public static void main(String[] args)
{
ConnectToDB();
}
public static void ConnectToDB()
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e)
{
System.out.println("\nOracle JDBC driver not found");
e.printStackTrace();
return;
}
System.out.print("\nOracle JDBC Driver Registered");
Connection connection=null;
Statement stmt=null;
try
{
connection = DriverManager.getConnection("jdbc:oracle:thin:@192.168.171.166:1521:orcl","payroll",
             "payroll");
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select emp_code,emp_name,date_of_birth from employee_master");
File file = new File("/sub/aaa.csv");
if(!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.print("\n" + lpad("Emp Code",10) + "|" + lpad("Emp Name",50) + "|" + lpad("Date of Birth",20));
while(rs.next())
{
System.out.print("\n" + lpad(rs.getString("emp_code"),10) + "|" + lpad(rs.getString("emp_name"),50) + "|" + lpad(rs.getString("date_of_birth"),20));
bw.write("\n" + lpad(rs.getString("emp_code"),10) + "|" + lpad(rs.getString("emp_name"),50) + "|" + lpad(rs.getString("date_of_birth"),20));
}bw.close();
rs.close();
connection.close();
}
catch(SQLException e)
{
System.out.print("\nConnection Failed! Check output console");
e.printStackTrace();
return;
}
catch(IOException e)
{
e.printStackTrace();
return;
}
if(connection!=null)
System.out.print("\nSuccess");
else
{
System.out.print("\nFailed");
return;
}
}
public static String lpad(String s,int l)
{
String gap="";
for(int i=s.length();i<=l;i++)
gap+=" ";
return gap + s;
}

public static String rpad(String s,int l)
{
String gap="";
for(int i=s.length();i<=l;i++)
gap+=" ";
return s + gap;
}
}

No comments: