I am trying to insert question in question table and than getting that latest question id. I am trying to add options for it in other table named select_op. It inserts question successfully but not options. Even I am not getting any exception, method exits successfully.
int id=addQuestions(ques, survey_id);
if(id>0){
//not inserting anyvalue in database
String sql = "insert into select_op("+ "first,"+ "second,"+ "third,"+ "four,"+ "question_id)"+" values(?,?,?,?,?)";
try {
conn.setAutoCommit(false);
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1,option1);
pst.setString(2,option2);
pst.setString(3,option3);
pst.setString(4,option4);
pst.setInt(5,id);
pst.addBatch();
System.out.println(pst.executeBatch());
}catch (BatchUpdateException e) {
try {
System.out.println(e);
conn.rollback();
} catch (Exception e2) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//this function insert data successfully
public int addQuestions(String ques,String survey_id){
String sql = "insert into question(question,survey_id) values(?,?)";
int id = 0;
try {
conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1,ques);
pstmt.setString(2,survey_id);
pstmt.addBatch();
pstmt.executeBatch();
ResultSet keys = pstmt.getGeneratedKeys();
keys.next();
id = keys.getInt(1);
keys.close();
conn.commit();
pstmt.close();
}
catch (BatchUpdateException e) {
try {
conn.rollback();
} catch (Exception e2) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return id;
}
Any Suggestion?
As Zaki Suggested
Are you missing a commit ?
I did commit.. Solved :)
Thanks
getGeneratedKeys() may not be supported in mysql (I've never seen it used or tried it).
But I do know this works: Executing the query select mysql_insert_id() returns the last auto increment value - use that instead of getGeneratedKeys().
Related
I am trying to run a PLSQL script which I have as a string value with the following method.
I first create the procedure
then I create a callStatement to call it
and finally I add some parameters
I get the error message:
ORA-06575: Package or function PROCEDURE_NAME is in an invalid state
Any ideas what I can do about that?
This is the code:
public IResult createAndExecuteCallable(String queryText, String procedureName, Object[] parameter) {
IResult result = new Result();
String procedure = "create procedure "+procedureName+"("+queryText+")";
Connection connection = this.getDatabaseConnection().getConnection();
try {
connection.setAutoCommit(true);
Statement stmt = connection.createStatement();
stmt.executeUpdate(procedure);
CallableStatement statement = connection.prepareCall("call "+procedureName+"()");
commonPreparedStatment(statement,parameter);
try {
statement.executeUpdate();
} catch(SQLException se){
result = new Result(se);
} finally {statement.close();}
} catch(Exception e){
result = new Result(e);
} finally {
closeConnection(connection);
}
return result;
}
Thanks to the comments and some other help I found the solution. Here is the new middle part of the code, now including compilation:
connection.setAutoCommit(true);
PreparedStatement createStatement = connection.prepareStatement(queryCreateText);
PreparedStatement compileStatement = connection.prepareStatement(queryCompileText);
CallableStatement statement = connection.prepareCall(queryCallText);
commonPreparedStatment(statement, parameter);
try {
createStatement.executeUpdate();
log.info("create ok");
} catch (SQLException ignored) {
log.info(ignored.getMessage());
} finally {
log.info(queryCompileText);
createStatement.close();
}
try {
compileStatement.executeUpdate();
log.info("compile ok");
} catch (SQLException ignoredToo) {
log.info(ignoredToo.getMessage());
} finally {
compileStatement.close();
}
try {
statement.executeUpdate();
log.info("execute ok");
} catch (SQLException se) {
result = new Result(se);
} finally {
statement.close();
}
One additional obstacle was the file content of the plsql code. It contained line breaks and Oracle did not accept them. So I had to remove them before creating the procedure in Oracle:
queryCreateText = queryCreateText.replace("\r\n", " ");
I want to insert values for multiple columns of a table. I am doing an Eclipse Project and I want to feed the data from my project into the database. There are multiple columns in the database and I have values for each of these columns from my Eclipse Project. The JDBC driver and the connections are all done. I just need to figure out how to input these values from the project into the table.
public void insert(Double num1, Double num2, Double result) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
PreparedStatement stmt = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Calculator", "root", "");
stmt = con.prepareStatement("INSERT INTO RESULT(ID,VALUE1,VALUE2,RESULT) VALUES (?,?,?,?))");
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
}
}
}
}
You're close to an answer, your are missing the setXXX calls to assign values to the ? in your insert statement, you didn't provide a value for ID in your function parameter and you have an extra parenthesis in the prepareStatement.
stmt = con.prepareStatement("INSERT INTO RESULT(ID,VALUE1,VALUE2,RESULT) VALUES (?,?,?,?)");
// stmt.set___(1,___);
stmt.setDouble(2,num1);
stmt.setDouble(3,num2);
stmt.setDouble(4,result);
I'm trying to figure out how to rollback commits from multiple methods. I want to do something like the following (editing for brevity)
public void testMultipleMethodRollback() throws DatabaseException {
Connection conn = connect();
fakeMethodRollback1();
fakeMethodRollback2();
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
and currently all my methods are formatted like this
public void fakeMethodRollback1() throws DatabaseException {
Connection con = connect();
PreparedStatement ps = null;
ResultSet rs = null;
// insert some queries
try {
String query = "some query";
ps = conn.prepareStatement(query);
ps.executeUpdate(query);
query = "some query";
ps = conn.prepareStatement(query);
ps.executeUpdate(query);
con.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
throw new DatabaseException(e);
} finally {
close(rs, ps, conn);
}
}
because I want to be able to use the other methods independently, how can I do a rollback where if one method fails, the others will roll back? I fear I have my whole class setup wrong or at least wrong enough that this can't be accomplished without major work. I can't change the methods to return a connection, because half of my methods are get methods, which are already returning other data. Any ideas?
I am using a PreparedStatement to insert into mysql,I get no error but data has not been inserted,when I check in the mysql console it says Empty set:
public void insertGeometryValues(String gisuniqkey,String objkey,String objtype,String geometry)
{
PreparedStatement statement=null;
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values(?,?,?,?);";
try {
conn.setAutoCommit(false);
statement=(PreparedStatement) conn.prepareStatement(sql);
statement.setString(1, gisuniqkey);
statement.setString(2,geometry);
statement.setString(3,objtype);
statement.setString(4,objkey);
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I also tried using a Statement like this and get this ERROR
try {
if(conn==null)
{
System.out.println("The connection was not initialized.");
return false;
}
Statement st=(Statement) conn.createStatement();
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values('"+gisuniqkey+"','"+geometry+"','"+objtype+"',"+objkey+"');";
System.out.println(sql);
rc=st.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Your use of PreparedStatement never actually executes the statement. Change your code to:
public void insertGeometryValues(String gisuniqkey,String objkey,String objtype,String geometry) {
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values(?,?,?,?);";
conn.setAutoCommit(false);
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setString(1, gisuniqkey);
statement.setString(2,geometry);
statement.setString(3,objtype);
statement.setString(4,objkey);
statement.executeUpdate(); // <---- This is what is missing!
conn.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have also included try-with-resources so that the statement is actually correctly closed.
the answer given by Mark is correct. that should help you inserting using prepared statement.
You Sql query for inserting using Statement is incorrect. you have missed the starting ' for objkey variable. the correct query is
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY, GEOMETRY,OBJTYPE,OBJKEY) values('"+gisuniqkey+"','"+geometry+"','"+objtype+"','"+objkey+"');";
I get this exception while truncating all table in a schema.
I truncate 3 schema in my Java code and first method get list of table names from given schema name and second method executes "TRUNCATE TABLE table_name" query.
I confused about my code always succesful while truncating first and third schema. But while executing on second schema I get ORA-01000 error.
My truncate code is
private void truncateTable(Connection conn, String tableName) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(Utility.TRUNCATE_TABLE + tableName);
ps.executeUpdate();
} catch (SQLException e) {
log.error("SQLException occured while getting table names from schema", e);
} finally {
Utility.free(ps, null, null);
}
}
private List<String> getAllTableNames(Connection conn) {
PreparedStatement ps = null;
ResultSet rs = null;
List<String> list = new ArrayList<String>();
try {
ps = conn.prepareStatement(Utility.SELECT_ALL_TABLE_NAMES);
rs = ps.executeQuery();
while (rs.next()) {
list.add(rs.getString("TABLE_NAME"));
}
} catch (SQLException e) {
log.error("SQLException occured while getting table names from schema", e);
} finally {
Utility.free(ps, rs, null);
}
return list;
}
public static void free(PreparedStatement ps, ResultSet rs, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.error("Error occurred while closing ResultSet",e);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
log.error("Error occurred while closing PreparedStatement",e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.error("Error occurred while closing Connection",e);
}
}
}
What is the wrong about code or is it about schema configuraiton in Oracle?
How can I solve this?
If are you iterating over the List generated by getAllTableNames and calling truncateTable in a tight loop, your free calls in the finally block might just be delayed and stacking up to an extent that they aren't clearing fast enough for the next iterations - since you only know the finally will be called at some point, not necessarily immediately and before control is returned to the caller.
The schema size would make a difference to that, so it might make sense that a small schema succeeds and a large one fails. If that is what's happening then you should call free inside the try, as well as in the finally:
private void truncateTable(Connection conn, String tableName) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(Utility.TRUNCATE_TABLE + tableName);
ps.executeUpdate();
Utility.free(ps, null, null);
ps = null;
} catch (SQLException e) {
log.error("SQLException occured while getting table names from schema", e);
} finally {
if (ps != null) {
Utility.free(ps, null, null);
}
}
}
If Utility.free checks whether ps is null then that check in the finally block might be redundant, but without it, free would be called twice if there is no SQLException.
Check out the code and make sure you are closing the cursors after being used. If the problem still persists please set OPEN_CURSORS to some more value.