在Java中收到错误“ ORA-00942:表或视图不存在”

时间:2019-09-13 05:50:22

标签: java oracle jdbc

我正在尝试学习连接到oracle数据库

当我以这种方式登录sqlplus时:

sqlplus sys/Oracle_1@orcl as sysdba;

我运行以下代码:

connect hr/hr@orclpdb

select count(*) from employees;

我得到以下输出:

 COUNT(*)
----------
       107

但是当我尝试用Java代码访问该表时,出现此错误:

ORA-00942: table or view does not exist

这是我的Java代码:

class OracleCon{  
public static void main(String args[]){  
try{  
Class.forName("oracle.jdbc.driver.OracleDriver");  
Connection con=DriverManager.getConnection(  
        "jdbc:oracle:thin:hr/hr@localhost:1521/orclpdb","sys as sysdba","Oracle_1"); 
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select count(*) from employees");  
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
con.close();  
}catch(Exception e){ System.out.println(e);}  

}  
}  

我应该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:3)

您正在尝试在Java代码中使用sys用户进行连接,但是employee模式中存在表hr

您可以更改:

//Change this line from

Connection con=DriverManager.getConnection(  
        "jdbc:oracle:thin:hr/hr@localhost:1521/orclpdb","sys as sysdba","Oracle_1"); 

// to

Connection con=DriverManager.getConnection(  
        "jdbc:oracle:thin:hr/hr@localhost:1521/orclpdb","hr","hr"); 

您可以更改从表employee获取数据的方式(使用其架构查询表)

//Change this line from
ResultSet rs=stmt.executeQuery("select count(*) from employees"); 
//to
ResultSet rs=stmt.executeQuery("select count(*) from hr.employees"); 

干杯!

答案 1 :(得分:1)

请尝试此代码。必须工作

public static void conn() throws ClassNotFoundException, SQLException{  
    Connection con=DriverManager.getConnection(  
            "jdbc:oracle:thin:@localhost:1521:orclpdb", "HR", "HR"); 
    Statement stmt=con.createStatement();  
    ResultSet rs=stmt.executeQuery("select count(*) from dual");  
    while(rs.next())  
        System.out.println(rs.getInt(1));  
    con.close();
}