//学习链接: https://www.bilibili.com/video/BV14E411Q7wJ?p=2
package com.librarySystem;
import jdk.nashorn.internal.ir.RuntimeNode;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.Formatter;
public class ConnnectDatabase {
public static void main(String args[]) {
try {
//1、加载驱动 从左侧的lib文件夹中获得
Class.forName("oracle.jdbc.OracleDriver");
//2、建立与数据库连接 需要
// 主机地址 连接本机 localhost 或者127.0.0.1
// 端口号 Oracle 数据库默认端口号 1521
// 实例名 安装全的是orcl,没有安装全的是XE
String url = "jdbc:oracle:thin:@localhost:1521:orcl"; // jdbc:oracle:thin: @主机地址 : 端口号 : 实例名
// 下面的user和password是在sqlplus上可以登录的账户和密码
String user = "cc";
String password = "ccpassword";
Connection conn = DriverManager.getConnection(url, user, password);
if (!conn.isClosed()){
System.out.println(conn);
}else {
System.out.println("Sorry,failed connecting to the Database");
}
//3、创建语句对象
Statement statement=conn.createStatement();
//4、执行SQL语句
String sql ="SELECT * FROM Reader";
ResultSet resultSet = statement.executeQuery(sql);
//5、处理结果
while(resultSet.next()){
//打印当前行的值
String rno = resultSet.getString("RNO");
String rname= resultSet.getString("RNAME");
String rsex = resultSet.getString("RSEX");
int rage = resultSet.getInt("RAGE");
String rboss = resultSet.getString("RBOSS");
String raddress = resultSet.getString("RADDRESS");
Formatter f = new Formatter();
f.format("%4s\t%6s\t%4s\t%-3d\t%6s\t%5s",rno,rname,rsex,rage,rboss,raddress);
System.out.println(f);
}
//6、释放资源
resultSet.close();
statement.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}