How to verify if my JDBC query output has data in it or not - jdbc

I want to verify if my JDBC query output has data in it or not. If it doesn't contain any data then it should print the assertion as false.
I tried using this:
System.out.println("Table contains "+rs.getRow()+" rows");
if (!rs.next())
{
Assert.assertTrue(false);
}
else
{
Assert.assertTrue(true);
}
I tried using as below:
System.out.println("Table contains "+rs.getRow()+" rows");
if (!rs.next())
{
Assert.assertTrue(false);
}
else
{
Assert.assertTrue(true);
}
But it didn't work. So can anyone suggest how to solve this?

If you only need to know, how many rows are in a table, let the DBMS count them with:
select count(*) as noRows from table
And within your java code it will look like this snippet
boolean hasRows= false;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery("select count(*) as noRows from table");
if ( rs.next() ) {
if ( rs.getInt(1) > 0 ) {
hasRows = true;
}
}
} catch (SQLException sqlex ) {
// print or log an error message
} finally {
if ( rs != null ) {
try {
rs.close();
} catch (SQlException sqlex ) {
// print or log an error message
}
}
if ( stmt != null ) {
try {
stmt.close();
} catch (SQlException sqlex ) {
// print or log an error message
}
}
}
Assert.assertTrue(hasRows);
And it could also make sense to close your connection.
This will just return the rows within a table. If you need to know the size of a particular query, I for myself would do it similarly with the query and just replace the fields from the query with the count(*) or count(DISTINCT xyz) command. Try it first out within your sql monitor, because if the query runs to long, you might not be happy.

Related

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+"%");

How to bind oracle params in scala?

i have done of code that it executes any query in scala it works perfect unless if my query has to use same parameter twice. the database version is 12 and the oracle jar is ojdbc6, i wrote this code in order to execute query
def executeQuery(locale: String, query: String, input: Map[String, String], output: List[String]): Vector[Map[String, Any]] = {
var connection: Connection = null;
val properties = ConnectionLoader.getConnectionProperties(locale);
try {
connection = getDBConnection(properties);
val statement = connection prepareCall (query)
if (null != input)
for ((k, v) <- input) {
statement.setObject(k, v)
}
for (k <- output) {
statement.registerOutParameter(k, OracleTypes.INTEGER)
}
val resultSet = statement.executeQuery();
realize(resultSet);
} catch {
case e => throw e;
} finally {
if (null != connection)
connection.close();
}
}
and my query is
SELECT COUNT (1)
FROM ORDERS
WHERE ORDER_ID = :P_ORDER_ID AND STATUS_ID = 4
this query works fine but im getting an error when executing
SELECT COUNT (1)
FROM ORDERS
WHERE ORDER_ID = :P_ORDER_ID AND STATUS_ID = 4 and :P_ORDER_ID=9
Regardless to this unlogical query i'm getting this error
Execution exception[[SQLException: Missing IN or OUT parameter at index:: 2]]
i have googled everything but i got no result please advise

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.

How to use jmeter to test an Oracle Stored Procedure with sys_refcursor return type?

I want to test an Oracle Stored Procedure by using jmeter.I have done everything but parameters.
And here is my SQL Query:
declare
outinfo varchar2(20);
outtable sys_refcursor;
begin
{call RK_JSCX(?,?)};
end;
The outtable in Oracle is a cursor.And i used resultSet to contain it in java.However,whatever i set in parameter types ,it said invalid type.
Sample Start: 2012-10-25 16:06:41 CST
Load time: 0
Latency: 0
Size in bytes: 25
Headers size in bytes: 0
Body size in bytes: 25
Sample Count: 1
Error Count: 1
Response code: null 0
Response message: java.sql.SQLException: Invalid data type: cursor
Response headers:
oracle.jdbc.driver.T4CConnection#58ba09
SampleResult fields:
ContentType: text/plain
DataEncoding: UTF-8
How can fix it?
Thanks!
Here is my code in java:
public String RK_JSCX() throws Exception {
RK_JSCX_Response response = null;
List<RK_JSCX_Outtable> list = null;
Connection con = null;
CallableStatement cs = null;
ResultSet rs = null;
String sql = null;
try {
sql = "{call RK_JSCX(?,?)}";
con = ConnectionUtils.getInstance().getConnect();
if (con.isClosed()) {
throw new IllegalStateException("ERROR.THE CONNECTION ISCLOSED");
}
cs = con.prepareCall(sql);
cs.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
rs = (ResultSet) cs.getObject(1);
list = new ArrayList<RK_JSCX_Outtable>();
while (rs.next()) {
RK_JSCX_Outtable out = new RK_JSCX_Outtable(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5), rs.getString(6));
list.add(out);
}
String outInfo = cs.getString(2);
response = new RK_JSCX_Response(list, outInfo);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (rs != null) {
rs.close();
if (cs != null) {
cs.close();
}
if (con != null) {
con.close();
}
}
} catch (SQLException e) {
System.out.println("Exception2");
e.printStackTrace();
}
}
return JSON.toJSONString(response);
}
This is how to do it:
SQL Query : call RK_JSCX(?,?)
Parameter values : OUT, OUT
Parameter types : OUT -10,OUT VARCHAR
-10 being the int value of OracleTypes.CURSOR
Variable names: cursor, outInfo
Names are what you want
JMeter allows using more types than java.sql.Types constants, in this case instead of using Constant names, you use integer values of constants.
Documentation has been clarified (in next JMeter version) , see:
https://issues.apache.org/bugzilla/show_bug.cgi?id=54048
Try with the following changes
change the syntax in calling the procedure to
cs = con.prepareCall("BEGIN RK_JSCX(?, ?); END;");
And I believe your first OUT parameter is VARCHAR2 right? so
cs.registerOutParameter(1, Types.VARCHAR);
then
use the following to cast CallableStatement
rs = ((OracleCallableStatement)cs).getCursor(2);
Update 1
I have changed your procedure to demonstrate working version
Procedure
CREATE OR REPLACE PROCEDURE rk_jscx (outtable OUT sys_refcursor,
outinfo OUT VARCHAR2
)
AS
BEGIN
OPEN outtable FOR
SELECT SYSDATE
FROM DUAL;
outinfo := 1;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
outinfo := 2;
ROLLBACK;
END rk_jscx;
Java Code
CallableStatement stmt = conn.prepareCall("BEGIN rk_jscx(?, ?); END;");
stmt.registerOutParameter(1, OracleTypes.CURSOR);
stmt.registerOutParameter(2, Types.VARCHAR);
stmt.execute();
ResultSet rs = ((OracleCallableStatement)stmt).getCursor(1);
while (rs.next()) {
System.out.println(rs.getDate("sysdate"));
}
The above prints 2012-10-23
Check your jdbc driver as well

How to append text to an oracle clob

Is it possible to append text to an oracle 9i clob without rereading and rewriting the whole content?
I have tried this:
PreparedStatement stmt = cnt.prepareStatement(
"select OUT from QRTZ_JOBEXEC where EXEC_ID=? "
+ "for update",
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
try {
stmt.setLong(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
Clob clob = rs.getClob(1);
long len = clob.length();
Writer writer = clob.setCharacterStream(len+1);
try {
PrintWriter out = new PrintWriter(writer);
out.println(line);
out.close();
} finally {
writer.close();
}
rs.updateClob(1, clob);
rs.updateRow();
}
rs.close();
} finally {
stmt.close();
}
But I'm getting an "Unsupported feature" exception on the call to setCharacterStream.
DBMS_LOB.APPEND is the key.
if you are just adding text then you could try a simple
UPDATE qrtz_jobexec SET out = out || ? WHERE exex_id=?

Resources