public static void main(String[] args) {标签:pre,jdbc,String,results,sql,Oracle,null,连接,conn From: https://www.cnblogs.com/cpp826/p/17384072.html
//声明连接对象、执行sql对象、结果集对象
Connection conn = null;
PreparedStatement pre = null;
ResultSet results = null;
//添加jar驱动
try{
//注册驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//获取连接数据库对象
String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
String name = "SCOTT";
String pwd = "cpp123456";
//DriverManage初始化时会扫描到注册的Driver实例
conn = DriverManager.getConnection(url,name,pwd);
System.out.println("连接成功");
//定义要执行的sql
String sql = "SELECT * FROM SCOTT.STUDENT";
//获取执行sql对象
pre = conn.prepareStatement(sql);
//执行SQL并返回结果集
results = pre.executeQuery();
System.out.println("执行成功");
while(results.next()){
System.out.println("学生名:"+results.getString("STUDNETNAME"));
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (results != null)
results.close();
if (pre != null)
pre.close();
if (conn != null)
conn.close();
System.out.println("数据库连接已关闭!");
} catch (Exception e) {
e.printStackTrace();
}
}
}