Oracle connection in java (error is invalid column name)

泪湿孤枕 提交于 2020-01-06 08:37:30

问题


    public static void baglanti(){

    OracleDataSource ods;
    //String driverName = "oracle.jdbc.driver.OracleDriver";

    try {
        ods = new OracleDataSource();
        ods.setURL("jdbc:oracle:thin:@//aaaaaa:2122/XXXXX");
        ods.setUser("aaaa");
        ods.setPassword("aaaa");

        Connection conn=ods.getConnection();
        Statement st=conn.createStatement();
        ResultSet rs=st.executeQuery("SELECT DESCRIPTION FROM example");

        while (rs.next()) {
            //rs.getString("ID");
            System.out.println("DESC : "+rs.getString("1"));

        }   

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



}

I have an error my connection java from to oracle.user name ,password are correct but I couldn't connect to db. Thanks.


回答1:


The way you use getString is wrong. You can pass an index or the column label:

System.out.println("DESC : "+rs.getString(1));

or

System.out.println("DESC : "+rs.getString("description"));

you pass the index as a String and that's wrong.




回答2:


Since you say you have a connection error, try below code for connection part:

OracleDataSource ds = new OracleDataSource();
ds.setDriverType("thin");
ds.setServerName("dssw2k01");
ds.setPortNumber(1521);
ds.setDatabaseName("orcl"); // sid
ds.setUser("scott");
ds.setPassword("tiger");

If the connection is correct and the query is executed, even then you will have issues parsing the resultset unless you correct the below one as:

System.out.println("DESC : "+rs.getString(1));

OR System.out.println("DESC : "+rs.getString("DESCRIPTION"));

rs.getString(), rs.getInt() etc all have either

  1. The index as an integer parameter starting from 1

or

  1. The alias name of the resultset output as a String


来源:https://stackoverflow.com/questions/24238188/oracle-connection-in-java-error-is-invalid-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!