简体   繁体   English

连接Java和Oracle数据库

[英]Connecting java and oracle data base

I am JAVA newbie and I am trying to connect my java code and oracle database, I followed some tutorial but it did not work. 我是JAVA新手,并且尝试连接Java代码和oracle数据库,我遵循了一些教程,但没有用。 This is my code. 这是我的代码。

  package probasem;



import java.sql.*;

public class Jedan {

     public static void main(String[] args) {

         try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr");

            Statement st = con.createStatement();
            String sql  = " select * from employees";
            ResultSet rs = st.executeQuery(sql);
                    while (rs.next())
                        System.out.println(rs.getInt(1) +  " "  + rs.getInt(2));

con.close();                        
        } catch (Exception e) {


            System.out.println(e);
        }

    }
}

It throws me an exception : 它引发了一个例外:
java.sql.SQLException: Fail to convert to internal representation java.sql.SQLException:无法转换为内部表示形式

also when I change the local host to 3036 I get this : 当我将本地主机更改为3036时,也会得到以下信息:

java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection java.sql.SQLRecoverableException:IO错误:网络适配器无法建立连接

Change the code to below: 将代码更改为以下代码:

System.out.println(rs.getInt(1) + " " + rs.getString(2)); 

As second column is firstname and is of type varchar2. 第二列是名字,其类型为varchar2。

Further, i recommend using column names instead of column position as they make code less error prone like this: 此外,我建议使用列名而不是列位置,因为它们会使代码更少出错,如下所示:

rs.getString("firstname");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM