UPSERT Query gives ORA Missing Expression Exception - java

I am trying to update and insert into Oracle Database by using this below query. But when I was trying to insert into oracle database by using this below query, I always get the exception as-
java.sql.SQLException: ORA-00936: missing expression
This is the below UPSERT Query- Is there anything wrong with this below query?
// Update and Insert both
public static final String UPSERT_SQL = "MERGE INTO " +DATABASE_TABLE+ " USING ( SELECT ? AS ID, " + // We will maybe add this record
" ? AS CGUID, " +
" ? AS PGUID, " +
" ? AS SGUID, "+
" ? AS USERID, "+
" ? AS ULOC, "+
" ? AS SLOC, "+
" ? AS PLOC, "+
" ? AS ALOC, "+
" ? AS SITEID, "+
" FROM dual ) maybe "+
// Checking whether ID got matched, if matched then we will update the database table (ULOC, SLOC, PLOC, ALOC)
" ON (maybe.ID = "+DATABASE_TABLE+".ID) "+
" WHEN MATCHED THEN "+
// We only need update the fields that might have changed
" UPDATE SET " +DATABASE_TABLE+ ".ULOC = maybe.ULOC, " +DATABASE_TABLE+ ".SLOC = maybe.SLOC, " +DATABASE_TABLE+ ".PLOC = maybe.PLOC, " +DATABASE_TABLE+ ".ALOC = maybe.ALOC "+
// If not matched then we will Insert new records in the database.
" WHEN NOT MATCHED THEN "+
// Insert new record
" INSERT VALUES (maybe.ID, maybe.CGUID, maybe.PGUID, maybe.SGUID, maybe.USERID, maybe.ULOC, maybe.SLOC, maybe.PLOC, maybe.ALOC, maybe.SITEID)";
And I am trying to insert like this-
LnPDataConstants.PSTMT = LnPDataConstants.DB_CONNECTION.prepareStatement(LnPDataConstants.UPSERT_SQL);
LnPDataConstants.PSTMT.setInt(1, (int) ind);
LnPDataConstants.PSTMT.setString(2, LnPDataConstants.CGUID_VALUE);
LnPDataConstants.PSTMT.setString(3, LnPDataConstants.PGUID_VALUE);
LnPDataConstants.PSTMT.setString(4, LnPDataConstants.SGUID_VALUE);
LnPDataConstants.PSTMT.setString(5, LnPDataConstants.UID_VALUE);
LnPDataConstants.PSTMT.setString(6, LnPDataConstants.ULOC_VALUE);
LnPDataConstants.PSTMT.setString(7, LnPDataConstants.SLOC_VALUE);
LnPDataConstants.PSTMT.setString(8, LnPDataConstants.PLOC_VALUE);
LnPDataConstants.PSTMT.setString(9, LnPDataConstants.ALOC_VALUE);
LnPDataConstants.PSTMT.setString(10, LnPDataConstants.SITEID_VALUE);
LnPDataConstants.PSTMT.executeUpdate();
And when I tried to print the query- I got like this on the console-
MERGE INTO LNPDATA USING ( SELECT ? AS ID, ? AS CGUID, ? AS PGUID, ? AS SGUID, ? AS USERID, ? AS ULOC, ? AS SLOC, ? AS PLOC, ? AS ALOC, ? AS SITEID, FROM dual ) maybe ON (maybe.ID = LNPDATA.ID) WHEN MATCHED THEN UPDATE SET LNPDATA.ULOC = maybe.ULOC, LNPDATA.SLOC = maybe.SLOC, LNPDATA.PLOC = maybe.PLOC, LNPDATA.ALOC = maybe.ALOC WHEN NOT MATCHED THEN INSERT VALUES (maybe.ID, maybe.CGUID, maybe.PGUID, maybe.SGUID, maybe.USERID, maybe.ULOC, maybe.SLOC, maybe.PLOC, maybe.ALOC, maybe.SITEID)

" ? AS SITEID, "+
" FROM dual ) maybe "+
remove comma.

You still need to list the columns for your insert statement
WHEN NOT MATCHED THEN
INSERT (col1, col2 ... )
VALUES (val1, val2 ... )

Related

PreparedStatement set Where clause [duplicate]

This question already has answers here:
How to use a tablename variable for a java prepared statement insert [duplicate]
(4 answers)
Closed 4 years ago.
I'm using PreparedStatement for a DELETE query.
My ps is configured as this
config.sql.statement.delete=DELETE FROM ? WHERE ?
Then in my Java code, I set values like this
ps.setString(1, schemaName == "F" ? "FUNDS" : "MANDATE" + "." + tableName);
ps.setString(2, whereClause);
The whereClause is set up as below
String whereClause = " ";
for (int m = 0; m < columns.size(); m++) {
String columnData = jsonObj.getString(columns.get(m));
log.info("Column Data for column " + columns.get(m) + " Value: " + columnData);
if (m == 0) {
whereClause = whereClause + columns.get(m) + " = " + "'" + columnData + "'";
} else {
whereClause = whereClause + " AND " + columns.get(m) + " = " + "'" + columnData + "'";
}
}
log.info("WHERE CLAUSE: " + whereClause);
whereClause is being logged as this:
WHERE CLAUSE: CLIENT_END_DT = '9998-12-31' AND CLIENT_START_DT = '2017-04-06' AND FUND_CODE = 'TEST_CODE'
ERROR that I got:
com.microsoft.sqlserver.jdbc.SQLServerException: An expression of non-boolean type specified in a context where a condition is expected, near '#P1'.
After google a bit, I noticed that it might be related to how I configure WHERE clause. Any exact problem with the way I use this ps?
With PreparedStatement you cannot use database object names i.e. table, columns as parameter.
In your sql query, use specific names for both table and columns, in order to avoid SQL injections.
DELETE FROM table_name WHERE column1 = ? and column2 = ?
Perhaps, you may use your custom placeholder for the same as work around, beware of SQL attacks !
config.sql.statement.delete=DELETE FROM $table WHERE $whereClause
Later build your sql as:
String sql = ...; /* your logic */
sql = sql.replace("$table",(schemaName == "F" ? "FUNDS" : "MANDATE" + "." + tableName));
sql = sql.replace("$whereClause",whereClause);
ps=conn.prepareStatement(sql);

SQL Insert Into a newly created column ,data placed after the last row of the previous column

I have a problem with a SQL statement. I have a java app with a button to add a column into a database. For every new date, I have a new column created, which is done using the following query
final String queryCreate = "alter table Currency add '"+ newColumn + "' decimal ";
When I try to populate the column with data using the following query:
final String queryAdd = "insert into Currency( '" + newColumn + "' ) values(1.95583)";
The data is added below the last row of the previous column.
like this:
https://postimg.org/image/579gjmyzj/
My question is why the insert statement does what it does in my situation, what am I doing wrong?
INSERT creates new records, if you want to modify existing records you need to use UPDATE.
For example, to modify the first record:
"UPDATE Currency SET " + newColumn + " = 1.95583 WHERE Currency_ID = 1"
use update query
assuming strCurrencyID="1";
strCurrencyName="EUR";
final String queryAddUpdate =
if exists(Select Top 1 1 from Currency where Currency_ID=" + strCurrencyID +")
Begin update Currency set " + newColumn + "=1.95583 where Currency_ID=" +strCurrencyID + "
End
Else
Begin
insert into Currency(Currency_id, Currency_name, '" + newColumn + "' ) values("+ strCurrencyID +",'" + strCurrencyName + ", 1.95583)
End"
This will update the value in in column if currency id exists if not this will insert new row.
But I think database design should be change can you explain your business requirement.

update current date and time to db using sql from Java code

i have a table "queue_in_progress" whose structure is like the following :
I want to update the DATE_TIME_TOKEN_TAKEN , CE_PK , Service_status of the table . For this , I have the following code :
String sqlQuery = "UPDATE queue_in_progress\n" +
"SET CE_PK="+ce_pk+" ,SERVICE_STATUS=1 \n" +
"WHERE CATEGORY_PK="+Category_PK+" AND TOKEN_NO="+ Token_PK+" "
+ " AND SERVICE_COUNTER="+service_counter+" AND SERVICE_CENTER_PK="+service_center+" ;";
java.util.Date utilDate = new Date(); // Convert it to java.sql.Date
java.sql.Date date = new java.sql.Date(utilDate.getTime());
PreparedStatement stmt = con.prepareStatement(sqlQuery);
stmt.setDate(1, date);
success = stmt.executeUpdate();
But the success flag is returning -1 and the table is not updated . What is the problem ? What can I do to fix this problem ?
I don't see DATE_TIME_TOKEN_TAKEN=? in your query (the bind parameter), I think you wanted
String sqlQuery = "UPDATE queue_in_progress SET DATE_TIME_TOKEN_TAKEN=?, "
+ "CE_PK=" + ce_pk
+ ", SERVICE_STATUS=1 WHERE CATEGORY_PK="
+ Category_PK
+ " AND TOKEN_NO="
+ Token_PK
+ " AND SERVICE_COUNTER="
+ service_counter + " AND SERVICE_CENTER_PK=" + service_center;
OR if you want DATE_TIME_TOKEN_TAKEN to ALWAYS hold Current Time value, you can Set it on your Database side, no need to set it in your code.
ALTER TABLE queue_in_progress
MODIFY DATE_TIME_TOKEN_TAKEN DEFAULT CURRENT_TIMESTAMP;

how to update a sql varchar column using JAVA handle createStatement INNO DB

I need to update my columns using JAVA Handle and create statement, but from what I have researched I need to be using batch if its all (or most) of the columns I desired to update?
This is the code i've written thus far:
private int deletePlayer(Handle handle, String username, String table) {
logger.debug("Deleting from table " + table);
String sqlCommand;
sqlCommand = String.format("UPDATE %s SET rank = 1 "
+ "SET level = 1 "
+ "SET exp = 0 "
+ "SET prof = '' "
+ "SET guild = '' "
+ "SET varname = '' "
+ "WHERE name = :username", table);
handle.createStatement(sqlCommand)
.bind("username", username)
.execute();
return 1;
}
I broke it up to try and pinpoint the problem and found that the MySQL Command:
sqlCommand = String.format("UPDATE %s SET varname = '' WHERE name = :username", table);
And the like is not working. This is more than likely because of the string/char concatenation.
Also, should I be using batch instead?
Stack Trace: [Ljava.lang.StackTraceElement;#15b2043
Please, if you are going to make this post down please tell me why and I will be more than happy to fix it to your liking, or clarify, so that it adheres to the forum conduct/terms of service/ et cetera.
I think you missed the comma between keyword set to update DB values.
sqlCommand = String.format("UPDATE %s SET rank = 1 "
+ "SET level = 1, "
+ "SET exp = 0, "
+ "SET prof = '', "
+ "SET guild = '', "
+ "SET varname = '' "
+ "WHERE name = :username", table);

fetch value from SQL query list

So i just wrote down this SQL query and i am trying to capture the value of rest_id in query.list(). However, this is giving the value as [1] . I want just 1 without the braces. How do i do it? Please check the code below for reference:
String sql1 = "select rest_id from rest_details where rest_name = '" + nameclicked + "' and rest_location = '" +locclicked + "'" ;
SQLQuery query1 = session.createSQLQuery(sql1);
System.out.println("sql1 " + query1.list());
Use below code to get the element inside list:
System.out.println("sql1 " + query1.list().get(0));
This always returns only the first element from the list.
Replace
System.out.println("sql1 " + query1.list());
By :
for(String id : query1.list() ) System.out.println("sql1 " + id);

Categories

Resources