您的位置:首页 > 数据库 > Oracle

jdbc连接oracle

2018-10-22 17:38 92 查看
[code]public static void main(String[] args) {
String driver = "oracle.jdbc.OracleDriver";    //驱动标识符
String url = "jdbc:oracle:thin:@localhost:1521:orcl"; //链接字符串
// url ="jdbc:oracle:thin:@10.0.30.64:1521:orcl";  // 连接远程的数据库可以这么写
String user = "scott";         //数据库的用户名
String password = "tiger";     //数据库的密码
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
boolean flag = false;

try {
Class.forName(driver);
con = DriverManager.getConnection(url,user, password);
String sql = "select * from emp";
pstm =con.prepareStatement(sql);
rs = pstm.executeQuery();
while(rs.next()) {
int empno = rs.getInt("empno");
String ename =rs.getString("ename");
double sal = rs.getDouble("sal");
Date hiredate =rs.getDate("hiredate");
int deptno = rs.getInt(("deptno"));
System.out.println(empno +"\t"+ ename +"\t"+ sal +"\t"+ hiredate +"\t"+ deptno);
}

flag = true;
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e) {
e.printStackTrace();
}
finally {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

// 关闭执行通道
if(pstm !=null) {
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

// 关闭连接通道
try {
if(con != null &&(!con.isClosed())) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}

if(flag) {
System.out.println("执行成功!");
} else {
System.out.println("执行失败!");
}
}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: