ResultSet with binary data [duplicate] - java

This question already has answers here:
Does a ResultSet load all data into memory or only when requested?
(5 answers)
Closed 6 years ago.
I have a simple Java 6 code:
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/db?user=u&password=p");
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM "+tabela);
while(res.next()){
byte[] fileBytes = res.getBytes(fileColumnIndex);
fos.write(fileBytes);
}
So my question is - does ResultSet load all data to some local memory at once, or does it load it by chunks on every res.next()?

Simply check the Javadoc:
https://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html
You are moving through your result from the executed SQL query, row by row, column by column (by the index or the column name)
(Don't forget to free resources when you are done with your result set).
About your question, consider as a programmer the ResultSet as the same concept to the Stream: "you can't do anything about the past, you don't know the future, you can only process the present"

Related

will closing a prepared statement close the resultset associated to it? [duplicate]

This question already has answers here:
When is ResultSet closed?
(3 answers)
Closed 5 years ago.
I have a function which returns a resultset which is associted to a prepared statement.i am closing the prepared statement in the finally block.
it automatically closes the resultset also which i need to return.
what is an alternative way for this?
My code looks like this
Resultset fnName(){
Resultset rs = null;
PreparedStatement ps = new PreparedStatement();
try{
rs = ps.execute(<query string>);
}
catch(...){...}
finally{
ps.close().
}
return rs;
}
You could have read the Javadoc (my emphasis):
void close​()
throws SQLException
Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources.
Calling the method close on a Statement object that is already closed has no effect.
Note: When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

How to read Stored Procedure source code from a java program? [duplicate]

This question already has answers here:
How to see PL/SQL Stored Function body in Oracle
(3 answers)
Closed 5 years ago.
I need to read the contents(text inside a stored procedure) of a stored procedure of a particular schema from a Java program.
Example. suppose I have a sp in oracle named mySp.
I need to read the text inside the sp.
How i can achieve this from a java program.
I think you can use something like this..Better refer JDBC MetaData API..Hope this helps
http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html
DatabaseMetaData dbMetaData = conn.getMetaData();
ResultSet rs = dbMetaData.getProcedureColumns(conn.getCatalog(),
null,
"mySp",
"");
while(rs.next()) {
/
}

PreparedStatement for select count [duplicate]

This question already has answers here:
passing table and column name dynamically using bind variables
(2 answers)
Closed 8 years ago.
I have a program that will count the number of records from a variety of data sources. I have the database names and table names stored in array lists called database_names and table_names respectively. I am unable to get this to run:
for (int i = 0; i < table_names.size(); i++) {
String query = "select count(1) from ?.?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, database_names.get(i));
stmt.setString(2, table_names.get(i));
ResultSet rs = stmt.executeQuery();
}
I get an ORA-00903: invalid table name error. I have set print statements to ensure that my database_names.get(i) and table_names.get(i) were printing out the right values. They were, and if I hardcode the database name and table name into my query string, the program is able to count the records.
How can I properly prepare my query statement so that it is of the form:
select count(1) from database_name.table_name
Oracle says: When you prepare a SQL statement or PL/SQL block that contains input data to be supplied at runtime, placeholders in the SQL statement or PL/SQL block mark where data must be supplied.
Schema and table name are not data, but data structures. During prepare phase Oracle parses statement, checks privileges. optimises plan. This is not possible without schema and tablename.
Oracle uses bind variables in execution phase, when your statement is prepared.
In your case you have to create new PreparedStatement for each table

Difference between CreateStatement and PreparedStatement in JDBC [duplicate]

This question already has answers here:
Difference between Statement and PreparedStatement
(15 answers)
Closed 9 years ago.
Hi I am trying to learn JDBC.
and here is my question:-
What is the Use of PreparedStatement in JDBC Because We can achieve the same effect by using createStatement(); too.
I mean if there is a query like:
Select * from tbl_name where id = somevalue
Then We can achieve it by both PreparedStatement and createStatement(). As follows:
Using CreateStatement():
try {
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter id :- ");
int id=Integer.parseInt(dis.readLine());
String q="Select * from tbl_name where id="+id;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(q);
while(rs.next()) {
//fetching part
}
} catch(Exception ex){ ... }
Using PreparedStatement:
try {
PreparedStatement preStatement=conn.prepareStatement("Select * from tbl_name where id=?");
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter id:- ");
int id=Integer.parseInt(dis.readLine());
preStatement.setInt(1, id);
ResultSet result = preStatement.executeQuery();
while(result.next()){
// fetch the data
}
}catch(Exception ex){ ... }
As both of these programs are capable of doing the same task.
Why there is provision of two different Methods? Also looping seems to be easy if avoid repeatation is the answer.
Can any one tell me which one is good to use ?
what is the provision of each of them?
What is the difference between them, and which one optimizes the code?
The prepared statement concept is not specific to Java, it is a database concept. Precompiling of statement means, when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution.
The advantages of Prepared Statements are:
As the execution plan get cached, performance will be better.
It is a good way to code against SQL Injection as escapes the input values.
When it comes to a Statement with no unbound variables, the database is free to optimize to its full extent. The individual query will be faster, but the down side is that you need to do the database compilation all the time, and this is worse than the benefit of the faster query.
With the createStatement the underlying database has to parse and compile the passed select query every time the statement is executed. This can impact performance. You can kind of "save" the query logic in a prepared statement and just pass in the query parameters, which could be the variable part of your query, every time the statement is executed.

When is ResultSet closed?

I want to know if ResultSet can be closed if I didn't close it ? I have a ResultSet is closed exception but I am sure I didn't close the ResultSet anywhere .
What I do exactly is that I use the ResultSet to perform a SELECT query then I use the same ResultSet because it's called by this method :
public Object getValueAt( int row, int column )
throws IllegalStateException {
// ensure database connection is available
if ( !dbConnection.isConnectedToDatabase() )
throw new IllegalStateException( "Not Connected to Database" );
// obtain a value at specified ResultSet row and column
try {
getResultSet().absolute( row + 1 );
return getResultSet().getObject( column + 1 );
} // end try
catch ( SQLException sqlException ) {
System.out.println("Exception from here dude");
sqlException.printStackTrace();
} // end catch
return ""; // if problems, return empty string object
} // end method getValueAt
So , another question : Is there a way to ensure the ResultSet is opened ?
Third question : Maybe the problem because I never close ResultSets .
What's the point of closing ResultSet ?
Edit : That's how statement is being created inside the constructor of a class called DBConnection:
Class.forName(driver);
// connect to database
connection = DriverManager.getConnection(url, username, password);
// create Statement to query database
statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY );
//connection ok
connectedToDatabase=true;
ResultSet is created later whenever I want to execute a statement.
Directly from the docs on ResultSet.close():
Releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.
...
Note: A ResultSet object is automatically closed by the Statement object that generated it when that Statement object is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results.
So, if you closed the Statement that generated your ResultSet is closed, you get that exception.
Another question's answer: you shouldn't read results from a ResultSet like that. Perform the select an read all the data you need from the ResultSet at once, close the connection and then later you can read the fetched data as much as you want. You really shouldn't have an external resource/class calling your getValueAt method, which you expect to still be connected to the database. Connection may be terminated for many other reasons, so that's not the way to go.
Third answer: answered above.
Last answer: releasing resources explicitly, without waiting for it to be closed when Statement is.
In case you have closed any of the following, your ResultSet will be closed automatically:
Statement object.
Connection object.
I am strongly suspecting the connection is being closed. It is a natural tendency to close the database connection once the query is run. While it is a good practice, but may be you are closing the connection even before you have used the ResultSet object inside your TableModel class.
I always close Connections, ResultSets and Statements in finally {} block. In such case I don't have this problem, since this block is always executed (Well, not always, but here it fits). Please refer to this post, I placed skeleton implementation that might be interesting for you.

Categories