通过Java连接Oracle数据库

时间:2014-01-07 08:56:09

标签: java database oracle prepared-statement

我有一个与oracle数据库的基本连接,我得到了前两个打印语句,即连接到数据库并回读要插入的查询,但我没有到达行updateQuery = statement.executeUpdate();,因此声明没有执行。

我没有收到错误,我已经下载了ojdbc驱动程序,有什么建议吗?

 import java.sql.DriverManager;
 import java.sql.Connection;
 import java.sql.SQLException;
 import java.sql.PreparedStatement;

public class conn1 {

    public static void main(String[] argv) {

        //Scanner out = new Scanner(String);
        //In Java, we use plain JDBC calls to insert a record in STUDENTS table. We use sequence STUDENT_SEQ to generate primary key. 
        //Once the record is inserted, we want the last inserted primary value.

        PreparedStatement statement = null;
        int updateQuery = 0;
        String QUERY = "INSERT INTO SYS.STUDENTS (student_id, NAME, EMAIL, BIRTH_DATE)"
                + "VALUES ('1','Hermoine', 'Hermoine@hogwarts.edu', '08-Nov-1987')";

        // load oracle driver
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // get database connection from connection string
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:attendanced", "louise", "Attend123!");
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        if (connection != null) {
            System.out.println("Successfullly connected to Oracle DB");

            try {
                statement = connection.prepareStatement(QUERY);
                System.out.println("Insert This Query :" + QUERY);
                updateQuery = statement.executeUpdate();   //Erroneous line.

                if (updateQuery != 0) {
                    System.out.println("Record inserted successfully");
                } else {
                    System.out.println("Error, Record not inserted");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Failed to connect to Oracle DB");
        }
    }
}

0 个答案:

没有答案