Created
September 3, 2013 22:17
-
-
Save sathish-io/6430342 to your computer and use it in GitHub Desktop.
Basic JDBC Test Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.satlabs.helper; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.PreparedStatement; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
public class DBConnectionHelper { | |
public static Connection getConnection(String jdbcUrl, String userName, String passwd) throws SQLException, ClassNotFoundException { | |
Connection connection = null; | |
Class.forName("oracle.jdbc.driver.OracleDriver"); | |
System.out.println("Trying to connect to url - " + jdbcUrl + " with userName "+ userName + ", passwd " + passwd); | |
connection = DriverManager.getConnection(jdbcUrl, userName, passwd); | |
System.out.println("Connected to DB"); | |
return connection; | |
} | |
public static void closeConnection(Connection connection) { | |
if(connection != null) { | |
try { | |
connection.close(); | |
} catch (SQLException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} | |
public static void testConnection(Connection connection) { | |
PreparedStatement pstmt= null; | |
ResultSet rset= null; | |
try { | |
pstmt= connection.prepareStatement("select * from dual"); | |
rset = pstmt.executeQuery(); | |
rset.next(); | |
System.out.println( rset.getString(1)); | |
System.out.println("Test Success!!"); | |
} catch (SQLException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} finally { | |
if(rset != null) { | |
try { | |
rset.close(); | |
} catch (SQLException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
if(pstmt != null) { | |
try { | |
pstmt.close(); | |
} catch (SQLException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
pstmt= null; | |
rset= null; | |
} | |
} | |
public static void main(String[] args) { | |
String jdbcUrl ="jdbc:oracle:thin:@192.168.1.1:1521:mydb"; | |
String userName ="user"; | |
String passwd ="passwd"; | |
Connection con = null; | |
System.out.println("Started DBConnection Test"); | |
try { | |
con = getConnection(jdbcUrl, userName, passwd); | |
} catch (SQLException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} catch (ClassNotFoundException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
testConnection(con); | |
System.out.println("Completed DBConnection Test"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment