第一步:导入驱动包,这个包在Oracle安装目录下可以找到,例如:E:\Oracle\product\12.2.0\dbhome_1\jdbc\lib;

第二步就是写代码了

 1 import java.sql.Connection;
 2 import java.sql.DriverManager;
 3 import java.sql.SQLException;
 4 
 5 public class DBUtil {
 6     private static String username="c##scott";
 7     private static String password="tiger";
 8     private static String diver="oracle.jdbc.OracleDriver";
 9     private static String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl";//如果是服务器则这儿应该改成ip:1521:xe
10     
11     public static Connection getConnection() {
12         Connection connection=null;
13         try {
14             Class.forName(diver);
15             connection=DriverManager.getConnection(url, username, password);
16             
17         } catch (ClassNotFoundException e) {
18             // TODO Auto-generated catch block
19             throw new RuntimeException("class not find!", e);
20         } catch (SQLException e2) {
21             // TODO Auto-generated catch block
22             throw new RuntimeException("get connection error!", e2);
23         }
24         return connection;
25         
26     }
27     
28 }

 

public class test {
    public static void main(String []args){
        Connection connection=DBUtil.getConnection();
        String sql="select * from student";
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        System.out.println("OK");
        try {
            preparedStatement=connection.prepareStatement(sql);
            resultSet=preparedStatement.executeQuery();
            while(resultSet.next()){
                String id=resultSet.getString("id");
                String name=resultSet.getString("name");
                System.out.println(id+"\t"+name);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}
test.java

这样就OK了