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");
}
}
CodePudding user response:
There are 3 different JDBC execute functions:
PreparedStatement.execute
is for executing any statement; including DDL statements such asCREATE TABLE
, etc.PreparedStatement.executeQuery
is for executingSELECT
statements.PreparedStatement.executeUpdate
is for executing DML statements such asINSERT
,UPDATE
,DELETE
orMERGE
.
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.
CodePudding user response:
For inserts and deletion, it should be executeUpdate().
ResultSet resultSet = preparedStarement.executeUpdate();
CodePudding user response:
The problem is on ResultSet resultSet=preparedStatement.executeQuery();
executeQuery() is only for selects if you want to insert so you must use preparedStatement.execute();
or preparedStatement.executeUpdate();