Search code examples
javaoraclejdbcwhile-loopuser-input

user inputs not show in database table?


I'm trying to teach myself java(my English is not good sorry). after giving some inputs I tried to show(the values using select * from emp;) it on the table but rows are not creating what should I do to get the user input to (database)

public static void main(String[] args) throws SQLException, ClassNotFoundException {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
    
    PreparedStatement preparedStatement= connection.prepareStatement("insert into emp values(?,?,?)" );
    
    Scanner scanner = new Scanner(System.in);
    
    while (true) {
        
        System.out.println("enter eid");
        int eid = scanner.nextInt();
        System.out.println("enter ename");
        String ename = scanner.next();
        System.out.println("enter esal");
        double esal = scanner.nextDouble();
        
        preparedStatement.setInt(1, eid);
        preparedStatement.setString(2, ename);
        preparedStatement.setDouble(3, esal);
        System.out.println("data insert successfull....do you want add one more recored(yes/no)");
        String option = scanner.next();
        
        
        if(option.equals("no")) 
            break;
        
    }
    
       scanner.close();
       preparedStatement.close();
       connection.close();
       System.out.println("resource are closed");
    
}

}


Solution

  • There are 3 different JDBC execute functions:

    • PreparedStatement.execute is for executing any statement; including DDL statements such as CREATE TABLE, etc.
    • PreparedStatement.executeQuery is for executing SELECT statements.
    • PreparedStatement.executeUpdate is for executing DML statements such as INSERT, UPDATE, DELETE or MERGE.

    You want PreparedStatement.executeUpdate and not PreparedStatement.executeQuery.

    You also need to check that your statement/transaction is committing the data; if it is not then you need to explicitly COMMIT the data.