Oracle MERGE and java prepared statement - oracle

I have the below code whose sql script works perfectly on sql developer but when used in java code i.e
String MergeSQLMapping = "MERGE INTO test.test_table USING dual ON (CLN_POL_CODE = 22222) "
+ "WHEN MATCHED THEN "
+ "UPDATE SET COMPANY_NAME = 'kevin', POL_ID = '22222', MAPPED_BY = '22222' "
+ "WHEN NOT MATCHED THEN INSERT (COMPANY_NAME, POL_ID, CLN_POL_CODE, MAPPED_BY) "
+ "VALUES ('kevin', '22222', '22222', 'workerservice'); ";
System.out.println(MergeSQLMapping);
dbMergeConnection = DBConnection.getStagingConnection();
try {
PreparedStatement ps = dbMergeConnection.prepareStatement(MergeSQLMapping);
ps.execute();
dbMergeConnection.commit();
ps.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
}
i get the following error
ORA-00933: SQL command not properly ended
Any help accorded will be appreciated.

Related

why I can not insert into oracle in jdbc?

My goal is to transfer a series of songs from the songs table in SQLite DB to a songs table in oracle DB. First I select the information from SQLite and then transfer it to the oracle's songs, but it gives the following error.
try {
ResultSet resultSet = sqliteConnectionStatement.executeQuery("select * from songs");
while (resultSet.next()) {
oracleConnectionStatement.execute("insert into songs values (" + resultSet.getInt("_id") +
"," + resultSet.getInt("track") +
",'" + resultSet.getString("title") +
"'," + resultSet.getInt("album") + ")");
}
System.out.println("data transferred with no error");
resultSet.close();
} catch (SQLException e) {
System.out.println("Oops!something went wrong! : " + e.getMessage());
e.printStackTrace();
}
output:
Oops! something went wrong! : ORA-00917: missing comma
java.sql.SQLSyntaxErrorException: ORA-00917: missing comma
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:630)
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:564)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1231)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:772)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:299)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:512)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:123)
at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:1200)
at oracle.jdbc.driver.OracleStatement.executeSQLStatement(OracleStatement.java:1820)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1472)
at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:2505)
at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:2460)
at oracle.jdbc.driver.OracleStatementWrapper.execute(OracleStatementWrapper.java:328)
at org.ISOFT.Main.main(Main.java:21)
Caused by: Error : 917, Position : 37, Sql = insert into songs values (1,2,'I Can't Quit You Baby',343), OriginalSql = insert into songs values (1,2,'I Can't Quit You Baby',343), Error Msg = ORA-00917: missing comma
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:637)
... 13 more
NEVER build an SQL statement using string concatenation. Your code will be vulnerable to SQL injection attacks and if you run the same query with different parameters then the SQL engine will need to parse it every time making everything slower.
Use a prepared statement and bind variables. The code will not be vulnerable to SQL injections attacks and the SQL engine will only need to parse it once and then can reuse the previous execution plan.
Something like (untested):
ResultSet resultSet;
try {
resultSet = sqliteConnectionStatement.executeQuery(
"select * from songs"
);
oracleConnectionStatement.setAutoCommit(false);
PreparedStatement stmt = oracleConnectionStatement.prepareStatement(
"INSERT INTO songs (id, track, title, album) VALUES (?, ?, ?, ?)"
);
while (resultSet.next()) {
stmt.setInt(1, resultSet.getInt("_id"));
stmt.setInt(2, resultSet.getInt("track"));
stmt.setString(3, resultSet.getString("title"));
stmt.setInt(4, resultSet.getInt("album"));
stmt.addBatch();
}
stmt.executeBatch();
oracleConnectionStatement.commit();
System.out.println("data transferred with no error");
} catch (SQLException e) {
System.out.println("Oops!something went wrong! : " + e.getMessage());
e.printStackTrace();
} finally {
// Close the result set
if (resultSet != null)
{
try {
resultSet.close();
} catch (Exception e){}
}
// Close the connections
try {
sqliteConnectionStatement.close();
} catch (Exception e){}
try {
oracleConnectionStatement.close();
} catch (Exception e){}
}

Result set doesn't have value

I am making board and now trying to make search function.
but values doesn't come out if I search keyword
I have tried to run on oracle with printed sql and parameter(optionText,searchText..) it worked fine but result set doesnt have value
public List<boardVO> getBoardList(String optionText,String searchText,int totalNum , int nowPage){
List<boardVO> list = new ArrayList<boardVO>();
try {
connectDB();
String sql = "select * from "
+ "(select rownum as rnum,recordno,userid,title,content,views,regdate from";
if(optionText!=null && !optionText.equals("") && searchText!=null &&!searchText.equals("")) {
sql += " (select * from boardlist where ? like ?))";
}else{
sql += " boardlist)";
}
sql += "where rnum>=? and rnum<=? order by recordno desc";
pstmt = conn.prepareStatement(sql);
int finalNum = totalNum -(5*(nowPage-1));
if(optionText!=null && !optionText.equals("") && searchText!=null &&!searchText.equals("")) {
pstmt.setString(1, optionText);
pstmt.setString(2, "%"+searchText+"%");
if(finalNum>4) {
pstmt.setInt(3, finalNum-4);
pstmt.setInt(4, finalNum);
}else {
pstmt.setInt(3, 1);
pstmt.setInt(4, finalNum);
}
}else {
pstmt.setInt(1, finalNum-4);
pstmt.setInt(2, finalNum);
}
rs = pstmt.executeQuery();
while(rs.next()) {
boardVO vo = new boardVO();
System.out.println("while");
vo.setRecordNo(rs.getInt(2));
vo.setUserid(rs.getString(3));
vo.setTitle(rs.getString(4));
vo.setContent(rs.getString(5));
/* System.out.println(vo.getContent()); */
vo.setViews(rs.getInt(6));
vo.setRegdate(rs.getString(7));
list.add(vo);
}
} catch (Exception e) {
System.out.println("get board list error");
e.printStackTrace();
}finally {
closeDB();
}
return list;
}
I think this is your problem:
(select * from boardlist where ? like ?)
It looks like you are trying to pass both a column name and a searchable value to your query: you can't do this with parameters. Both assignments will be treated as literals, so your executed code will be something like this:
select * from boardlist where 'COLUMN_NAME` like '%some string%'
Perfectly valid SQL, just won't return any results.
If this is the case you need to change the assemblage of the statement to include the column name ...
if(optionText!=null && !optionText.equals("") && searchText!=null &&!searchText.equals("")) {
sql += " (select * from boardlist where " + optionText + " like ?))";
}else{
... and remove the parameter assignment:
if(optionText!=null && !optionText.equals("") && searchText!=null &&!searchText.equals("")) {
pstmt.setString(1, "%"+searchText+"%");

SonarQube nonconstant String in SQL statements

I'm scanning my code with SonarQube and I'm getting the following bugs:
-A prepared statement is generated from a nonconstant String
-Nonconstant string passed to execute method on an SQL statement
I have an sql query to which I append based on some conditions.
Example:
PreparedStatement ps = null;
StringBuilder sql = new StringBuilder("UPDATE" + tableName + " SET some_field = ? WHERE a_field = a_value");
if (myObject.getField1() != null) {
sql.append(" AND Field1 = " + myObject.getField1());
}
if (myObject.getField2() != null) {
sql.append(" AND Field2 = " + myObject.getField2());
}
if (myObject.getField3() != null) {
sql.append(" AND Field3 = " + myObject.getField3());
}
if (myObject.getField4() != null) {
sql.append(" AND Field4 = " + myObject.getField4());
}
...
**ps = connection.prepareStatement(sql.toString());** //generating bug
if (myObject.getSomeField() == null) {
ps.setNull(1, nevermind);
} else {
ps.setString(1, myObject.getSomeField());
}
I tried passing a final String = sql.toString(); to the prepareStatement() function and it still generates the bug.
The issue that's being raised is that you're assembling your SQL command with concatenation: which table to update, which columns to set and what values to put in them.
You should find a way to hard code the table and columns and use parameter binding for the values.

Error while trying to load data into hive table

I was able to create a table into hbase using hive now I'm trying to load data into a hive table then overwrite the data into the hbase table :
public class HiveJdbcClient {
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
/**
* #param args
* #throws SQLException
**/
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e){
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/default", "", "");
Statement stmt = con.createStatement();
String tableNameHive = "hbase_trades";
String tableNameHbase= "trades";
stmt.executeQuery("drop table " + tableNameHive);
ResultSet res = stmt.executeQuery("create table " + tableNameHive + " (key string, value string) STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler' WITH SERDEPROPERTIES (\"hbase.columns.mapping\" = \":key,cf1:val\") TBLPROPERTIES (\"hbase.table.name\" = \"trades\")");
String sql = "show tables '" + tableNameHive + "'";
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
if (res.next()) {
System.out.println(res.getString(1));
}
sql = "describe " + tableNameHive;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(res.getString(1) + "\t" + res.getString(2));
}
String filepath = "/tmp/test_hive_server.txt";
sql = "load data local inpath '" + filepath + "' into table " + tableNameHive;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
stmt.executeQuery("insert overwrite " + tableNameHbase+"select * from"+tableNameHive);
}
}
and I get the following error:
Running: load data local inpath '/tmp/test_hive_server.txt' into table hbase_trades
Exception in thread "main" java.sql.SQLException: Query returned non-zero code: 10101, cause: FAILED: SemanticException [Error 10101]: A non-native table cannot be used as target for LOAD
at org.apache.hadoop.hive.jdbc.HiveStatement.executeQuery(HiveStatement.java:194)
at com.palmyra.nosql.HiveJdbcClient.main(HiveJdbcClient.java:53)
could someone tell me what's the problem??

running an SQL update statement in java

There are many questions related to this topic, but I couldn't find a solution to my problem.
I have a table of "products" which I am trying to update in netbeans. The SQL statements works in SQL dev, and I have double checked my connection etc.
update products
set pvolume = 2, pprice = 15
where productid = 3;
output: 1 rows updated.
but running in netbeans it won't execute. If I have missed some small syntax issue I apologize, but I really need help with this method.
public boolean editProduct(int ID, String name, int volume, int quantity, String description, int price) {
boolean success = false;
Connection con = ConnectionTools.getInstance().getCurrentConnection();
String SQLString1 = "UPDATE products "
+ "SET pname = ?, "
+ "pvolume = ?, "
+ "pquantity = ?, "
+ "pdescription = ?, "
+ "pprice = ? "
+ "WHERE productID = ?";
PreparedStatement statement = null;
try {
statement = con.prepareStatement(SQLString1);
statement.setString(1, name);
statement.setInt(2,volume);
statement.setInt(3, quantity);
statement.setString(4, description);
statement.setInt(5, price);
statement.setInt(6, ID);
statement.executeUpdate();
success = true;
}catch (Exception e){
System.out.println("Insertion error!");
System.out.println(e.getMessage());
}finally {
try {
statement.close();
} catch (SQLException e) {
System.out.println("Statement close error!");
System.out.println(e.getMessage());
}
}
return success;
}
Running through the debug it seems to run through the try as far as statement.setInt(6, ID) but then does not execute. Here is the output:
Insertion error!
ORA-00971: missing SET keyword
Any help/advice would be appreciated! Thanks
You have to use brackets: update products set (pvolume = 2, pprice = 15) where productid = 3

Resources