Package COM.XIAN.JDBC;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import Javax.servlet.jsp.jstl.sql.Result;
Import Javax.servlet.jsp.jstl.sql.ResultSupport;
public class OracleConnection {
/**
* Connect the ORA database
* @return Con
* @throws ClassNotFoundException
* @throws SQLException
* @author Jia Xiaoxian
*/
public static Connection Getoracleconnection () throws classnotfoundexception,sqlexception{
String driver= "Oracle.jdbc.driver.OracleDriver";
String url= "JDBC:ORACLE:THIN:@127.0.0.1:1521:ORCL";
Class.forName (driver);
Connection con=drivermanager.getconnection (URL, "Scott", "7758521");
return con;
}
/**
* Close the Ora connection channel
* @return
* @throws SQLException
* @author Jia Xiaoxian
*/
public void Freeresources (ResultSet resultset,preparedstatement pstatement,connection con) throws sqlexception{
if (resultset.isclosed () ==false)
Resultset.close ();
if (pstatement.isclosed () ==false)
Pstatement.close ();
if (con.isclosed () ==false)
Con.close ();
}
/**
* Query for SQL without parameters
* @return Result
* @throws Exception
* @author Jia Xiaoxian
*/
Public Result runselectsql (String sql) {
Connection Con=null;
PreparedStatement Pstatement=null;
ResultSet Resultset=null;
Result Result=null;
try {
Con=getoracleconnection ();
Pstatement=con.preparestatement (SQL);
Resultset=pstatement.executequery ();
Result=resultsupport.toresult (ResultSet);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
try {
Freeresources (ResultSet, pstatement, con);
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
return result;
}
/**
* Query for SQL with parameters
* @return Result
* @throws Exception
* @author Jia Xiaoxian
*/
Public Result Runselectsql (String sql,object[] params) {
Connection Con=null;
PreparedStatement Pstatement=null;
Result Result=null;
ResultSet Resultset=null;
try {
Con=getoracleconnection ();
Pstatement=con.preparestatement (SQL);
for (int i=0;i<params.length;i++) {
Pstatement.setobject (i+1, params[i]);
}
Resultset=pstatement.executequery ();
Result=resultsupport.toresult (ResultSet);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
try {
Freeresources (ResultSet, pstatement, con);
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
return result;
}
}
This article is from the "Jia Xiaoxian" blog, make sure to keep this source http://hackerxian.blog.51cto.com/9240575/1626889
JDBC Connection for Oracle