SQLException处理

时间:2015-04-27 06:10:33

标签: jdbc oracle11g

我正在尝试运行一个简单的Java程序,它从oracle数据库中获取数据并显示它。我连接了oracle数据库。这是我的代码:

DataHandler类:

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import oracle.jdbc.pool.OracleDataSource;

public class DataHandler {
    public DataHandler() {
        super();
    }
    String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
    //I already added the above line but still getting error.
    String userid = "scott";
    String password = "tiger"; 
    Connection conn;

    public void getDBConnection() throws SQLException{
        OracleDataSource ds;
        ds = new OracleDataSource();
        ds.setUser(jdbcUrl);
        conn = ds.getConnection(userid,password); 
    }

    Statement stmt;
    ResultSet rset;
    String query;
    String sqlString;

    public ResultSet getAllEmployees() throws SQLException{ 
        getDBConnection(); 
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        query = "SELECT * FROM emp ORDER BY empno";
        System.out.println("\nExecuting query: " + query);
        rset = stmt.executeQuery(query); 
        return rset;
    }
}

和JavaClient类一样 JavaCLient CLass:

import java.sql.ResultSet;
public class JavaClient {
    public JavaClient() {
        super();
    }
    public static void main(String[] args) throws Exception{
        DataHandler datahandler = new DataHandler();
        ResultSet rset = datahandler.getAllEmployees();

        while (rset.next()) {
        System.out.println(rset.getInt(1) + " " +
          rset.getString(2) + " " + 
          rset.getString(3) + " " + 
          rset.getString(4));
        }
    }
}

我没有编译错误,但在运行时我得到以下异常错误

错误:

Exception in thread "main" java.sql.SQLException: Invalid Oracle URL specified: OracleDataSource.makeURL
at oracle.jdbc.pool.OracleDataSource.makeURL(OracleDataSource.java:1277)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:185)
at student_attendence_iem.DataHandler.getDBConnection(DataHandler.java:22)
at student_attendence_iem.DataHandler.getAllEmployees(DataHandler.java:31)
at student_attendence_iem.JavaClient.main(JavaClient.java:9)

使用退出代码1退出流程。

请帮帮我。提前致谢。 :)

1 个答案:

答案 0 :(得分:1)

您尚未设置数据库的URL。
添加以数据库的URL为参数的setURL(url)方法。以下是代码。

n <- 50; p <- 20
x <- abs(rmatrix(n, p, rnorm, mean=4, sd=1))
x[1:10, seq(1, 10, 2)] <- x[1:10, seq(1, 10, 2)] + 3
x[11:20, seq(2, 10, 2)] <- x[11:20, seq(2, 10, 2)] + 2
rownames(x) <- paste("ROW", 1:n)
colnames(x) <- paste("COL", 1:p) 
annotation = data.frame(Var1 = factor(1:p %% 2 == 0, labels = c("Class1", "Class2")), Var2 = 1:10)
aheatmap(x, annCol = annotation, Rowv=FALSE)

此外,对于OracleDataSource ds; ds = new OracleDataSource(); ds.setURL(jdbcUrl); ,您尝试 setUser 并使用数据库网址,这是错误的。
您不必像以前那样使用setUser,因为您已经在以下代码行中执行此操作了ds.setUser(jdbcUrl);