使用Java连接池连接Oracle数据库
/*** Java调用Oracle的存储过程
*/
static void callableSatement()
{
Connection con = null;
CallableStatement callStmt = null;
try
{
con = DBService.getInstance().getConnection();
System.out.println("创建连接成功");
// 调用Oralce的存储过程luketest(?)
callStmt = con.prepareCall("BEGIN luketest(?); END;");
callStmt.setInt(1, 682);
System.out.println("调用Oralce的存储过程");
callStmt.execute(); /* 如果这里阻塞说明上面的store procedure正被独占访问/或者事务没有提交 */
System.out.println("存储过程执行成功");
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if (callStmt != null)
callStmt.close();
if (con != null)
con.close();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
}
/**
* 执行预编译SQL语句
*/
static void preparedStatement()
{
// 表示预编译的 SQL 语句的对象。
// SQL 语句被预编译并且存储在 PreparedStatement 对象中。然后可以使用此对象高效地多次执行该语句。
Connection conn = null;
PreparedStatement prepStmt = null;
ResultSet set = null;
try
{
conn = DBService.getInstance().getConnection();
prepStmt = conn.prepareStatement("select * from account_info where account_id=5000007");
set = prepStmt.executeQuery();
while (set.next())
{
System.out.print(" " + set.getInt("account_id"));
System.out.print(" " + set.getString("account_name"));
System.out.println(" " + set.getString("account_password"));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if (set != null)
set.close();
if (prepStmt != null)
prepStmt.close();
if (conn != null)
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/**
* 执行SQL
*/
static void statement()
{
// 执行大量的查询语句
for (int i = 0; i < 100; i++)
{
Connection conn = null;
Statement stmt = null;
ResultSet set = null;
try
{
conn = DBService.getInstance().getConnection();
stmt = conn.createStatement();
set = stmt.executeQuery("select * from account_info where account_id=5000007");
while (set.next())
{
System.out.print(i + " " + set.getInt("account_id"));
System.out.print(" " + set.getString("account_name"));
System.out.println(" " + set.getString("account_password"));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if (set != null)
set.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
页:
[1]