No ResultSet from stored procedure with temporary table with JDBC - java

I have a stored procedure which creates a temp table and populates the temp table. After populating it, it returns the rows inside the table with (SELECT).
When running it from MySQL workbench works tremendously but in JAVA with JDBC, the ResultSet is empty. I have gone through some posts which say that we should not use PreparedStatment but even Statement doesn't work.
For test, I divided the job in stored procedure. Now I call:
CallableStatement ps = connection.prepareCall("{CALL myProcedure(?)}");
ps.setString(1, "value");
ps.execute();
which creates the temp table and populates it. Thereafter with same connection I try to do
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM tmp_table");
Still ResultSet is empty. What can I do? Any help is appreciated.

Thank you folks for help!
I found the error. The error was in code.
I send a parameter when calling procedure. For testing purposes I did
SET #param = "value";
Later on, I removed it but I forgot to remove it when inserting data into temporary table which used that #param. MySQL somehow could see that #param and IN param is same because of name but JDBC could not see that and Therefore, it was not returning any data.

Related

Getting SQL Exception when trying to get the last auto-incremented value

I've been trying everything, nothing is working, I'm new to mysql and databases and I want to get the last auto-incremented id (primary key) (user_id) from a table, from java. So this: SELECT MAX(user_id) FROM database_user; works fine in mysql, I got that, but why can't I get the same thing from java??
PreparedStatement st = connection.prepareStatement("SELECT MAX(user_id) from database_user");
st.executeUpdate();
ResultSet rs = st.executeQuery();
int uid = rs.getInt(1);
System.out.println(uid);
This gives me java.sql.SQLException: (conn=213) the given SQL statement produces an unexpected ResultSet object
This isn't the only thing I tried, it's just the last one so far. If anyone could just shed some light I would greatly appreaciate it.
You are missing rs.next(); between executing the query and fetching from the result set. This is needed, to move the result set to the first row.
You also shouldn't have st.executeUpdate(). Just executing once is enough.

JDBC CallableStatement Stored Procedure CURSOR result set fetch

I want to export huge data from oracle to csv file. so i used simple JDBC select statement to get data in memory but and then write it to file, But data is very large of i am getting Out of memory exception. So i thought of using CallableStatement to call Stored Procedure which will return CURSOR with ResultSet as below :-
String getDBTableCursorSql = "{call getDBTableCursor(?,?)}";
callableStatement = dbConnection.prepareCall(getDBTableCursorSql);
callableStatement.setString(1, "test");
callableStatement.registerOutParameter(2, OracleTypes.CURSOR);
// execute getDBTableCursorSqlstore procedure
callableStatement.executeUpdate();
// get cursor and cast it to ResultSet
rs = (ResultSet) callableStatement.getObject(2);
// loop it like normal
while (rs.next()) {
String userid = rs.getString("ID");
String userName = rs.getString("NAME");
..
..
}
Oracle Proc :-
CREATE OR REPLACE PROCEDURE getDBTableCursor(
p_username IN DBUSER.USERNAME%TYPE,
c_dbuser OUT SYS_REFCURSOR)
IS
BEGIN
OPEN c_dbuser FOR
SELECT * FROM CUSTOMER WHERE USERNAME LIKE p_username || '%';
END;
Question 1 :-
does above ResultSet will fetch all the data in single shot ? or it will go to database for each rs.next(),
Question 2:-
is there any other approach which can deal with large data export to file in java using chunks so it wont get Out of memory issue?
I can't use pagination in this condition because of requirement.
Regarding your first question: the Oracle jdbc driver by default fetches 10 rows at a time. This can be verified or set to other value via standard jdbc:
https://docs.oracle.com/cd/E11882_01/java.112/e16548/resltset.htm#JJDBC28621

Read stored procedure source code from Sybase ASE 15.7 database

I want to get access to the source code of some stored procedures, which are stored in a Sybase ASE 15.7 database.
At the moment I copy the text manually in a textfile and read it via executed java-code from the disk.
Now it is my goal to improve this process: I will get the sourcecode directly from the database within my executed java-code.
Is that possible?
Sorry, I have no idea.
I have Rapid SQL to work on the database.
you could run an ISQL script that calls the stored procedure sp_helptext to get the code of the stored procedure. Hope this helps.
Vince's hint was to use the stored procedure sp_helptext. This stored procedure produces more than one resultset and caused me difficulties.
RobV's answer was to use the stored procedure sp_showtext. This seems the better solution, cause it returns only one resultset. But I tried it with jdbc and it ever throws in a sql exception ("must return a resultset").
After my fails I find another solution, which need against the other two answers only a execution of a select statement. This works for me! Here is the code:
StringBuffer sbSP = new StringBuffer();
String query = "select c.text "
+"from syscomments c, sysobjects o "
+"where o.id=c.id and o.name='"+spName+"' order by c.colid";
PreparedStatement stmt = connection.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
//loop over every row of the stored procedure
sbSP.append(rs.getString("text") + "\n");
}
Best use sp_showtext; it gives better formatted results (no broken SQL lines) than sp_helptext

Getting Incorrect return in java accessing sql database

This is the code im using in java to query the database
connect = DriverManager.getConnection (url, "user", "pass");
state = connect.createStatement();
String meetID = "SELECT GamerTag FROM backup";
ResultSet rs = state.executeQuery(meetID);
while(rs.next()){
System.out.println(rs.toString());
}
Im not getting the values of the row in the database im getting this instead
com.mysql.jdbc.JDBC4ResultSet#108137c9
You're printing the result of the toString method of the Recordset object, which appears to print out the object's name and hashcode.
Instead, try to print the value of a column. Perhaps using getString:
System.out.println(rs.getString("GamerTag"));
The documentation for Java's recordset looks confusing, you might be better off searching for examples.
What do you expect rs.toString() should do it will just print the hash of the resultsetObject if you want to get the column values you should do this way
while(rs.next()){
System.out.println(rs.getString("yourFirstColumnName")+" "+
rs.getString("yourSecondColumnName")+" "+
rs.getString("yourThirdColumnName"));
}
Really you should use PreparedStatement. In your case though you are not using any parameterizedQuery but One of the major benefits of using PreparedStatement is better performance. PreparedStatement gets pre compiled.
In database and there access plan is also cached in database, which allows database to execute parametric query written using prepared statement much faster than normal query because it has less work to do. You should always try to use PreparedStatement.
So you can do something like this
String query = "SELECT GamerTag FROM backup"
PreparedStatement st =connect.prepareStatement("query");
ResultSet rs = st.executeQuery();

Inserting variables with SQL in Java

I'm writing a webpage that takes input from a form, sends it through cgi to a java file, inserts the input into a database through sql and then prints out the database. I'm having trouble inserting into the database using variables though, and I was wondering if anyone would be able to help me out.
String a1Insert = (String)form.get("a1");
String a2Insert = (String)form.get("a2");
This is where I get my variables form the form (just believe that it works, there's a bunch more back end but I've used this before and I know it's getting the variables correctly).
String dbURL = "jdbc:derby://blah.blahblah.ca:CSE2014;user=blah;password=blarg";
Connection conn = DriverManager.getConnection(dbURL);
Statement stmt = conn.createStatement();
stmt.executeUpdate("set schema course");
stmt.executeUpdate("INSERT INTO MEMBER VALUES (a1Insert, a2Insert)");
stmt.close();
This is where I try to insert into the databse. It give me the error:
Column 'A1INSERT' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'A1INSERT' is not a column in the target table.
If anyone has any ideas that would be lovely ^.^ Thanks
java.sql.Statement doesn't support parameters, switching to java.sql.PreparedStatement will allow you to set parameters. Replace the parameter names in your SQL with ?, and call the setter methods on the prepared statement to assign a value to each parameter. This will look something like
String sql = "INSERT INTO MEMBER VALUES (?, ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "a1");
stmt.setString(2, "a2");
stmt.executeUpdate();
That will execute the SQL
INSERT INTO MEMBER VALUES ('a1', 'a2')
Notice the parameter indexes start from 1, not 0. Also notice I didn't have to put quotes on the strings, the PreparedStatement did it for me.
Alternatively you could keep using Statement and create your SQL string in Java code, but that introduces the possibility of SQL injection attacks. Using PreparedStatement to set parameters avoids that issue by taking care of handling quotes for you; if it finds a quote in the parameter value it will escape it, so that it will not affect the SQL statement it is included in.
Oracle has a tutorial here.

Categories