为什么访问数据库时控制台中没有输出?

时间:2018-06-15 15:21:58

标签: java eclipse oracle

这是我第一次使用Eclipse,而我正在尝试使用Java创建与数据库的连接。我一步一步地完成了这个过程,最后,当我点击运行时,控制台中没有输出。

我做错了什么?

import java.sql.*;

public class jdbcconnection {

        public static void main(String[] args) {
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "password");
            Statement stm=con.createStatement();
            String sql="select * from student";
            ResultSet rs=stm.executeQuery(sql);
            while(rs.next())
                System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getInt(4));
            con.close();

        }
        catch(Exception e)
        {
            System.out.println(e);

        }

    }
}

我的学生表:

SQL> select * from student;

    STU_ID STU_NAME     BRANC       YEAR
---------- ------------ ----- ----------
         1 xyz          mech           2
         2 abc          cse            2
         3 efg          cse            2

1 个答案:

答案 0 :(得分:0)

您的代码按预期工作;在您显示并通过Eclipse运行代码时创建和填充表格会在控制台中显示:

1 xyz mech 2
2 abc cs 2
3 efg cs 2

因此,您似乎已经通过SQL * Plus插入了这三行数据,但尚未提交它们。在Oracle中,已插入但未提交的数据对任何其他会话都不可见。表格本身是可见的 - 因为像create table这样的DDL会自动提交,因此您不会收到错误。但表中的数据尚不可见。

只需在插入语句(或退出,默认提交)之后在SQL * Plus会话中发出commit,例如:

create table student (stu_id number, stu_name varchar2(10), branch varchar2(5), year number);

insert into student (stu_id, stu_name, branch, year) values (1, 'xyz', 'mech', 2);
insert into student (stu_id, stu_name, branch, year)values (2, 'abc', 'cs', 2);
insert into student (stu_id, stu_name, branch, year)values (3, 'efg', 'cs', 2);

commit;

提交Eclipse会话后,将能够看到数据。

相关问题