How to check if column name exists when using Spring jdbcTemplate? - java

I am using jdbcTemplate to write data to my Oracle DB. I would like to reuse my code for the same table but in two different enviroments and the difference between these two enviroments is only one column missing. So before writing the data I need to check if the column is there or not to use the correct sql query, other I will get an exception. So I would like to have something like:
if(column3IsMissing){
String sql = String.format("insert into %s %s", MYTABLE,
"(column1, column2) values (?, ?)");
}else{
String sql = String.format("insert into %s %s", MYTABLE,
"(column1, column2, column3) values (?, ?, ?)");
}
jdbcTemplate.batchUpdate(sql, data, types);
Can anyone give me hint how should I implement the column3IsMissing check here? Thank you very much in advanced!

Oracle offer three different views to get table columns information: ALL_TAB_COLUMNS, USER_TAB_COLUMNS and DBA_TAB_COLUMNS.
You can run query like below with JDBC, to confirm if column exists before running your insert query.
select column_name from ALL_TAB_COLUMNS where TABLE_NAME = 'MYTABLE';

In order to get check the columns size. put all your column into array and check if
columnSize = 2.
String[] columnList = {column1,column2,column3);
if(columnList.size()==2){
String sql = String.format("insert into %s %s", MYTABLE,
"(column1, column2) values (?, ?)");
}else{
String sql = String.format("insert into %s %s", MYTABLE,
"(column1, column2, column3) values (?, ?, ?)");
}
jdbcTemplate.batchUpdate(sql, data, types);

Related

MySQL INSERT INTO doesn't work but gives no error

I'm having trouble inserting a row into a MySQL table with Java. I'm not sure what the problem is as it isn't giving an error. I'm trying to insert the row with the following:
String sql = "INSERT INTO users (uuid, authKey, code, scratches) VALUES (?, ?, ?, ?);";
PreparedStatement insertStmt = connection.prepareStatement(sql);
insertStmt.setString(1, uuid);
insertStmt.setString(2, key);
insertStmt.setInt(3, code);
insertStmt.setString(4, getScratchString());
insertStmt.executeUpdate();
The table 'users' is created successfully with no errors with the following:
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS users (uuid VARCHAR(40), authKey VARCHAR(30), code INT(10), scratches VARCHAR(45));");
When trying to insert the row with the same update in phpmyadmin, it works fine. There is no error given by the update so I have no idea where to start debugging. Any help would be appreciated. Thanks.
You have to do commit transaction check the below code
String sql = "INSERT INTO users (uuid, authKey, code, scratches) VALUES (?, ?, ?, ?)";
PreparedStatement insertStmt = connection.prepareStatement(sql);
insertStmt.setString(1, uuid);
insertStmt.setString(2, key);
insertStmt.setInt(3, code);
insertStmt.setString(4, getScratchString());
insertStmt.executeUpdate();
connection.commit();

return generated key preparedstatementsetter

I am trying to retrieve the generated key for an insert statement to an Oracle database. I'm using a PreparedStatementSetter with the jdbcTemplate. I've read the other StackOverflow post on this topic here, but the answer basically proposes moving away from StatementSetters. Is there a way to retrieve the key while using a PreparedStatementSetter? The documentation on using PreparedStatementSetters to retrieve keys is surprisingly sparse.
Here's my jdbcTemplate update statement:
statementSetter.setUpdatedBy(...);
statementSetter.setFileStatus(...);
statementSetter.setCompany(...);
int modifiedCount = jdbcTemplate.update(sql, statementSetter);
Here's my SQL string:
database.insertFileControlRecordQuery = INSERT INTO MY_TABLE \
(PRIMARY_KEY_FIELD, FIELD2, FIELD3,...) VALUES (MY_TABLE_SEQ.NEXTVAL, ?,?, ...)
Using a NEXTVAL as suggested in comments is potentially hazardous: if some other process does an insert and commit in between you fetching the NEXTVAL and committing your insert, you'll have a different key than what you assumed.
Instead, I would suggest using the update-function which has provisions for returning a key, i.e. ...
JdbcTemplate.update(PreparedStatementCreator, KeyHolder);
... from which you can determine the key.
An example to illustrate:
String insertQuery="INSERT INTO MY_TABLE (FIELD1, FIELD2) " +
"VALUES (?, ?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
PreparedStatementCreator preparedStatementCreator = connection -> {
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery, new String[]{"PRIMARY_KEY_FIELD"});
preparedStatement.setString(1, field1);
preparedStatement.setDate(2, field2);
return preparedStatement;
};
jdbcTemplate.update(preparedStatementCreator, keyHolder);
Number primaryKey = keyHolder.getKey();
Note that the setting of the column which holds the primary key upon creating the PreparedStatement is essential for Oracle! Without it, you'll be getting the ROWID instead.

How to insert with JdbcTemplate returning autogenerated id?

I want to make use of spring JdbcTemplate to insert a line and return the id autogenerated by the mysql db.
Without spring I'd do similar as follows:
String sql = "INSERT INTO mytable (id, filename, timestamp) VALUES (NULL, ?, NOW())";
Statement st = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
st.setString("test.csv");
st.executeUpdate();
st.getGeneratedKeys().next().getLong(1);
Question: how could I achive the same with JdbcTemplate?
In short its
Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(
parameters));
You can check my answer in identity from sql insert via jdbctemplate

How to Auto increment a column in mysql table through java

i have table with 2 columns 1.column1 2.column2(its unique)
now through java coding i am inserting data through 2 methods
in the first method i want to insert data ,in this coumn1 filed should be auto increment(for new user)
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
pstm = connection.prepareStatement(sql);
pstm.setInt(1, auto_incrmentvalue need to set);
pstm.setInt(2,column2);
in the second method insert data with what i want
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
pstm = connection.prepareStatement(sql);
pstm.setInt(1, column1);
pstm.setInt(2,column2);
how to set auto increment value in the first method
NOTE:Here column1 is not a primary key
INSERT INTO table(column1) SELECT MAX(column1)+1 FROM table
This one worked for me
Please see INSERT...SELECT
Your query should be like this,
INSERT INTO table(column1, column2) SELECT MAX(column1)+1, 79 FROM table
More refined answer:
INSERT INTO
usertable(column1, column2)
SELECT CASE COUNT(column1)
WHEN 0 THEN 0
ELSE MAX(column1) END+1,
79 FROM usertable
This could be a more simple solution:
INSERT INTO usertable(column1, column2)
SELECT IFNULL(MAX(column1)+1,1),79 FROM usertable
Lets try this once (not tested)
INSERT INTO table(column1) SELECT count(column1)+1 FROM table
For ex,
INSERT INTO table(column1, column2) SELECT count(column1)+1, 79 FROM table
if you want the auto value of column1, don't set it, just let it get a defult value
INSERT INTO table (column2) values(?)

java.sql.SQLException: ORA-00928: missing SELECT keyword. when inserting record to DB using JDBC

I get an error when I try to insert some rows to a db. so here is the code
try {
String insertStmt = "INSERT into " +
"MY_TABLE('RECORD_TYPE', 'FILE_TYPE', 'DATE', 'BATCH_NO', 'RECORD_COUNT')" +
"VALUES(?, ?, ?, ?, ?);";
PreparedStatement pstmt = super.con.prepareStatement(insertStmt);
pstmt.setString(1, input[0]);
pstmt.setString(2, input[1]);
pstmt.setString(3, input[2]);
pstmt.setString(4, input[3]);
pstmt.setString(5, input[4]);
System.out.println("Insert rows : " + pstmt.executeUpdate());
} catch (SQLException sqle) {
System.out.println(sqle.getMessage());
sqle.printStackTrace();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
con.close();
}
and everything on the db is of varchar type, double checked the columns (they all are the same name), took out the quotes off the column name (same result) no success. to add it up, the error message is not very helpful.
any suggestions would be appreciated.
You need to change the SQL statement. (Never use reserved words as identifiers)
String insertStmt = "INSERT into \"MY_TABLE\" (RECORD_TYPE,FILE_TYPE,
\"DATE\",BATCH_NO,RECORD_COUNT) VALUES (?, ?, ?, ?, ?)";
Use " (double quotes) to escape the reserved words/keywords.
I can spot two problems:
No need for single quotes around column names. But you may wrap it in double quotes. It is necessary if you are using reserved keywords for column names or table names. Here DATE.
You need a space before VALUES.
So you need to change insertStmt to somthing like this:
String insertStmt = "INSERT into " +
"MY_TABLE(RECORD_TYPE, FILE_TYPE, \"DATE\", BATCH_NO, RECORD_COUNT) " +
"VALUES(?, ?, ?, ?, ?);";
Print insertStmt String in Console and try to fire it in directly backend. It gives you exact error in backend. It seens some spacing or syntax error.
I just came to this page while searching for ORA-00928, and I'd like to note that my problem was an extra comma at the start of the column list:
INSERT INTO redacted.redacted
(
, redacted_id -- The comma at the start of this line will trigger ORA-00928.
, another_redacted_id
, redacted1
, redacted2
, redacted3
, created_at
, created_by
, changed_at
, changed_by
)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?)
For others searching for the same error: Other syntactical issues with the query can cause the same exception to be thrown. For example, omitting the word VALUES.
I was running the same issue, and in my case the query was like this:
insert into Address (number, street, id) values (?, ?, ?)
The problem was caused by the number column name since number is a reserved keyword in Oracle, and the exception was sort of misleading ORA-00928: missing SELECT keyword.
After escaping the number column, the statement was executed normally:
insert into Address ("number", street, id) values (?, ?, ?)

Categories

Resources