1. 程式人生 > >java後臺連接orcal數據庫(初學者)

java後臺連接orcal數據庫(初學者)

cti jdb nor null finally ger lec lose sys

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


public class ConnectionOrcalTest {

public static void main(String[] args) {
Connection con = null;
PreparedStatement pre = null;
ResultSet result = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url ="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
String user ="rcgl";
String password ="rcgl";
con = DriverManager.getConnection(url,user,password);
String sql = "select * from sys_user so where so.account=?";
pre = con.prepareStatement(sql);
pre.setString(1, "4425788");
result = pre.executeQuery();
while (result.next()){
// 當結果集不為空時
System.out.println("學號:" + result.getInt("account") + "姓名:"
+ result.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}finally
{
try
{
// 逐一將上面的幾個對象關閉,因為不關閉的話會影響性能、並且占用資源
// 註意關閉的順序,最後使用的最先關閉
if (result != null)
result.close();
if (pre != null)
pre.close();
if (con != null)
con.close();
System.out.println("數據庫連接已關閉!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

}

java後臺連接orcal數據庫(初學者)