public static void main(String[] args){
ResultSet rs=null;// 创建一个结果集对象
PreparedStatement pre=null;// 创建预编译语句对象,一般都是用这个而不用Statement
Connection conn=null;// 创建一个数据库连接
try{
Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
System.out.println("开始尝试连接数据库!");
String URL="jdbc:oracle:thin:@localhost:1521:test"; // test是Oracle的默认数据库名
String user="username";
String password="password";
//一个connection代表一个数据库连接
conn=(Connection) DriverManager.getConnection(URL,user,password);// 获取连接
String sql="Select*from emp";
//创建一个prepareStatement对象来蒋SQL语句发送到数据库
pre=conn.prepareStatement(sql); // 实例化预编译语句
rs=pre.executeQuery();// 执行查询,注意括号中不需要再加参数
System.out.print(pre+"\n");
System.out.print(rs+"\n");
//遍历
while(rs.next()){
System.out.print(rs.getString("name")+"\t");
System.out.print(rs.getString("age")+"\n");
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
// 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
// 注意关闭的顺序,最后使用的最先关闭
if(rs!=null){
rs.close();
rs=null;
}
if(pre!=null){
pre.close();
pre=null;
}
if(conn!=null){
conn.close();
conn=null;
System.out.println("数据库连接已关闭!");
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
利用JDBC连接Oracle数据库
最新推荐文章于 2024-07-19 20:18:03 发布