import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.util.Date;
public class JdbcTest{
publicstatic 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("执行失败!");
}
}
}
java通过jdbc操作数据库
猜你喜欢
转载自blog.csdn.net/wangchaox123/article/details/89532977
今日推荐
周排行