Select data from a temp table using java - java

I have a SQL stored procedure which select some data and insert to a temp table.
DECLARE #tmpTable TABLE ([record_Id] [int] NOT NULL)
WHILE(#count>0)
BEGIN
INSERT INTO #tmpTable
SELECT top 1 [record_Id]
FROM Table1
END
select * from #tmpTable
I used the following code to access the procedure
ResultSet rs=null;Statement stmt=null;
String getFirstRec="EXEC prod1";
stmt=con.createStatement();
rs=stmt.executeQuery(getFirstRec);
When I run this it gives me an error saying " the statement did not return the result set". can anyone help me to resolve this
Thanks

You want to use a CallableStatement which can be initialised from your connection using prepareCall()
Then use
CallableStatement callStat = con.prepareCall("EXEC prod1");
rs = callStat.executeQuery();

you should use prepareCall() for calling procedures
Have a look at here link
The above link clearly describes how to use procedures

Related

Get row count of successful bulk insert using jdbc from sql server

I have Java code to bulk-insert tab file to SQL Server.
I want to get the count of how many records were inserted. I tried using ##rowcount but I'm getting an error that "Statement did not return a result set".
If I run the bulk insert statement in management studio, I can get the count.
Statement stmt = sqlConnection.createStatement();
ResultSet rs = stmt.executeQuery ("BULK INSERT schema1.table1 FROM 'd:\temp1\file1.tab' SELECT ##rowcount");
Is there any way to get the inserted count?
I'm not familiar with SQL Server but it seems like you'll want to issue an executeUpdate instead of an executeQuery
Statement stmt = sqlConnection.createStatement();
int insertedRowCount = stmt.executeUpdate("BULK INSERT schema1.table1 FROM 'd:\temp1\file1.tab'");

Can I pass a list of String in the IN clause of sql statement(Oracle) using Java code

Can I pass a list of String in the IN clause of sql statement(Oracle 12c) using Java code.
My code is given below:
Connection con= abc.getConnection();
OracleConnection oracleConnection = null;
OraclePreparedStatement ops=null;
if (con.isWrapperFor(OracleConnection.class)){
oracleConnection= con.unwrap(OracleConnection.class);
}else{
// recover, not an oracle connection
}
PreparedStatement ps=oracleConnection.prepareStatement(sql);
if (ps.isWrapperFor(OraclePreparedStatement.class)){
ops= ps.unwrap(OraclePreparedStatement.class);
}else{
// recover, not an oracle connection
}
List<String >Ids=new ArrayList<String>();
Ids.add("12345");
Ids.add("12346");
java.sql.Array array1 = oracleConnection.createOracleArray("MY_NESTED_TABLE", Ids.toArray());
ops.setArray(1, array1 );
ResultSet rSet= ops.executeQuery();
I have defined my Oracle Nested Table as:
create or replace TYPE MY_NESTED_TABLE AS TABLE OF VARCHAR2(8 BYTE);
And the sql queries I tried to execute are:
SELECT * FROM MY_TABLE where MY_COLUMN IN (select column_value v from table(?))
SELECT * FROM MY_TABLE where MY_COLUMN IN (select column_value v from table(cast(? AS MY_NESTED_TABLE)))
There is no exception, just that I get no data in resultset.
I have seen people using this code working with PL/SQL. Should it work with a SQL statement as well?
Tested your approach and it is working fine. Please check if your mapping is correct and data is present in database.
Yes, you can use oracle arrays in sql statement.
How to create an oracle.sql.ARRAY object?

Call PostgreSQL stored procedure with Java returns null

I have the following stored procedure written in PostgreSQL 9.3 that's working perfectly:
CREATE OR REPLACE FUNCTION getColor(i INT)
RETURNS VARCHAR AS $varColor$
DECLARE varColor varchar;
BEGIN
select color into varColor FROM colors where id = i;
return varColor;
END;
$varColor$ LANGUAGE plpgsql;
In fact, when I execute select getColor(2) in pgAdmin I get the expected value.
I am trying to call it like this from Java (simplified version):
String call = "{ call getColor(?,?) }";
CallableStatement cstmt = connection.prepareCall(call);
cstmt.setInt(1, 2);
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR);
boolean hadResults = cstmt.execute();
The problem is that hadResults is always null.
Any ideas?
Postgresql stored procedures concept is something different than other vendors like Oracle.
Basically what in Oracle is called store procedure in Postgresql can be a function, and to call a function in Java is better to use prepare statements and executeQuery methods like in the following example
String call = "select getColor(?)";
PreparedStatement pstmt = connection.prepareStatement(call);
pstmt.setInt(1,1);
Resultset resultset = pstmt.executeQuery();
Thank you to all the guys who helped in the question comments!

How to use ref cursor to get multiple rows and retrieving them in Java?

The problem statement is like this :
I have to create a procedure to fetch all the data (only 9 records actually) in Employees1 table and then display that data by calling this procedure in Java. I am working on a legacy application that is built on struts 1.3 but that should not be of any concern here i guess.
Below is the procedure I created:
CREATE OR REPLACE PROCEDURE getALLEmployees(ref_cur out sys_refcursor)
IS
BEGIN
OPEN ref_cur FOR 'SELECT * FROM employees1';
END;
And here is my Java Code:
callableStatement = conn.prepareCall("{call getAllEmployees()}");
// Below line is (EmployeeDataJdbc.java:33) as mentioned in error
callableStatement.registerOutParameter(1,oracle.jdbc.driver.OracleTypes.CURSOR);
boolean isResultSet = callableStatement.execute();
rs = (ResultSet)callableStatement.getObject(1);
/*Employee paramater Order in DB
employee_id, employee_first_name, employee_last_name, employee_address,
employee_blood_group, employee_email, employee_department, employee_role,
employee_band, employee_mobile_number*/
while(rs.next()){
emp.setEmployeeId(rs.getInt(1));
emp.setEmployeeFirstName(rs.getString(2));
emp.setEmployeeLastName(rs.getString(3));
emp.setEmployeeAddress(rs.getString(4));
emp.setEmployeeBloodGroup(rs.getString(5));
emp.setEmployeeEmail(rs.getString(6));
emp.setEmployeeDepartment(rs.getString(7));
emp.setEmployeeRole(rs.getString(8));
emp.setEmployeeBand(rs.getString(9));
emp.setEmployeeMobileNumber(rs.getLong(10));
employeeList.add(emp);
}
This is the error I am getting at console:
Connected to Database
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterInternal(OracleCallableStatement.java:121)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:268)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:348)
at jdbcHandles.EmployeeDataJdbc.getEmployeeList(EmployeeDataJdbc.java:33)
I have not used PL-SQL since a long long time. Please help me find out where I am going wrong. Thanks in advance.
Note: I am using Oracle 10G express edition as database.
callableStatement = conn.prepareCall("{call getAllEmployees(?)}");
You have to mention where the out parameter has to be binded using the ?
And since the column count can change. Better have a check using the Metdatadata call rSet.getColumnCount()

Java CallableStatement registerOutParameter, what does it do?

I'm following a guide regarding callable statements.
In this guide, it says that I need to register the out parameter with the follow statement:
callsts.registerOutParameter(2, java.sql.Types.VARCHAR);
QUESTION: Why do I need to do this/what does it do ?
Complete Java code:
String getcall = "{call gettitle (?,?)}";
CallableStatement callsts = connect.prepareCall(getcall);
int nID = 15;
callsts.setInt(1, nID);
callsts.registerOutParameter(2, java.sql.Types.VARCHAR);
callsts.execute();
String calltitle = callsts.getString(2);
System.out.println("Callable Stamement Title: "+calltitle);
mySQL procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS `nothingtowear`.`gettitle` $$
CREATE PROCEDURE `nothingtowear`.`gettitle` (
IN nothingtowear_ID INT,
OUT nothingtowear_TITLE VARCHAR( 255 ))
BEGIN
SELECT Title INTO nothingtowear_TITLE
FROM articles
WHERE ID = nothingtowear_ID;
END $$
DELIMITER;
Out parameters are parameters passed to a SQL stored procedure that the procedure writes to.
In MySQL it can also be done via a SET command
SET out_param1 = value
See mysql stored-procedure: out parameter for another example
registerOutParameter will tell JDBC driver that it this is an otuput parameter and needs to be treated as such. E.g. it needs to use special syntax to call the procedure and retrieve output values after a statement is called
registerOutParameter is used to create a variable i.e. sql types on database server, so which is used to store value, and can get access using index in java calling stored procedures and functions context.
for example:
callableStatement.registerOutParameter(1, java.sql.Types.VARCHAR);
......
// get cursor and cast it to ResultSet
String var = callableStatement.getString(1);
In Oracle:
callableStatement.registerOutParameter(1, OracleTypes.CURSOR);
// get cursor and cast it to ResultSet
ResultSet rs = (ResultSet) callableStatement.getObject(1);

Categories

Resources