I'm a beginner in Java and am not understanding how to obtain a paragraph of text that I have stored in Mysql database as a Mediumblob through Java. Below is the section of my code that I'm having problems with. I've successfully obtained other stored data in the form of VARCHAR and INT through .getString() and .getInt(). I did try .getObject() below but that didn't seem to work. Any insight would be appreciated ~ thank you.
try{
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name = Clams;");
rs = pst.executeQuery();
while (rs.next()){
java.sql.Blob id = rs.getBlob("description");
System.out.print(id);
}
}catch(SQLException ex){
}finally {
try {
if (rs != null){
rs.close();
}
if (pst != null){
pst.close();
}
if (con != null){
con.close();
}
}catch(SQLException ex){
}
}
}
try this
java.sql.Blob id = rs.getBlob("description");
String s = new String(id.getBytes(0,id.length()));
Related
I have a code that looks like this,
Connection con = null;
PreparedStatement ps1 = null;
ResultSet rs1 = null;
try{
con = <someConnectionPool>.getConnection();
ps1 = con.prepareStatement(<someSQLString>);
rs1 = ps1.executeQuery();
while(rs1.next()){
PreparedStatement ps2 = null;
ResultSet rs2 = null;
try{
ps2 = con.prepareStatement(<someOtherSQLString>); // Sonar reports this prepared statement is not closed
rs2 = ps2.executeQuery(); // But no issue for this result set
while(rs2.next()){
System.out.println(rs2.getString(<someColumnName>));
}
}finally{
if(rs2 != null) rs2.close();
if(ps2 != null) ps2.close(); // But here, I am closing the ps2
}
}
}catch(Exception e){
// Exception logging here
}finally{
if(rs1 != null) rs1.close();
if(ps1 != null) ps1.close();
if(con != null && !con.isClosed()) con.close();
}
I am confused whether there is actually connection leak is there or is this some false positive reporting. And, as I have mentioned in the code, rs2 result set does NOT get reported as an issue. Only the prepared statement ps2 gets reported.
The problem with above code is in the finally block, if either rs1 or ps1 throw exception, con1 might not able to close. If you able to use Java 7 and above then consider using try-with-resources. If running on Java 1.6 and below then proper way should look like
if(rs1 != null) try {rs1.close();}catch(Exception e){//handle the given exception}
if(ps1 != null) try{ps1.close();}catch(Exception e){//handle the given exception}
if(con != null && !con.isClosed()) try {con.close();}catch(Exception e){//handle the given exception}
The java.sql.ResultSet#close() method may throw an exception:
SQLException - if a database access error occurs
If the following line
if(rs2 != null) rs2.close();
throws an exception, then ps2 is never closed.
I think there are a few things which could be improved in your code. First of all according to the ResultSet class JavaDoc:
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.
It means your code could be changed to:
Connection con = null;
PreparedStatement ps1 = null;
try {
con = <someConnectionPool>.getConnection();
ps1 = con.prepareStatement(<someSQLString>);
final ResultSet rs1 = ps1.executeQuery();
while (rs1.next()) {
PreparedStatement ps2 = null;
try {
ps2 = con.prepareStatement(<someOtherSQLString>);
final ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
System.out.println(rs2.getString(<someColumnName>));
}
} finally {
if (ps2 != null) ps2.close();
}
}
} catch (Exception e) {
// Exception logging here
} finally {
if (ps1 != null) ps1.close();
if (con != null && !con.isClosed()) con.close();
}
Next we need to make sure that connection is also always closed too:
Connection con = null;
PreparedStatement ps1 = null;
try {
con = <someConnectionPool>.getConnection();
ps1 = con.prepareStatement(<someSQLString>);
final ResultSet rs1 = ps1.executeQuery();
while (rs1.next()) {
PreparedStatement ps2 = null;
try {
ps2 = con.prepareStatement(<someOtherSQLString>);
final ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
System.out.println(rs2.getString(<someColumnName>));
}
} finally {
if (ps2 != null) ps2.close();
}
}
} catch (Exception e) {
// Exception logging here
} finally {
try {
if (ps1 != null) ps1.close();
} finally {
if (con != null) con.close();
}
}
This code works exactly as yours - when any close method throws an exception, it is also thrown by your method. I changed
if(con != null && !con.isClosed()) con.close();
to
if (con != null) con.close();
because (read JavaDoc)
Calling the method close on a Connection object that is already closed is a no-op.
It is also possible to rewrite try-catch to try-with-resources but I don't know which Java version you use.
I need to convert result set into csv for any database (not just postgres)
Empty csv file is being created when I use opencsv.
Here's the code of doGet method in the servlet:
final String JDBC_DRIVER = "org.postgresql.Driver";
final String DB_URL = "jdbc:postgresql://localhost:5432/postgres";
// Database credentials
final String USER = "postgres";
final String PASS = "12345";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
PreparedStatement ps = null;
Connection conn = null;
try {
// Register JDBC driver
Class.forName("org.postgresql.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
//stmt = conn.createStatement();
String sql = "SELECT * FROM users";
ps = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
/*if(rs.next()){
System.out.println("Name = "+rs.getString("first_name"));
}*/ //prints name so rs is not empty
//rs.first();
CSVWriter writer = new CSVWriter(new FileWriter("Test.csv"));
//even tried with seperator '\t' or ','
writer.writeAll(rs, true);
writer.close();
out.println("</body></html>");
// Clean-up environment
rs.close();
ps.close();
conn.close();
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (ps != null)
ps.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
} //end try
Not sure what's the error. Tried different way but csv is always empty.
Even tried writer.flush(), rs.beforeFirst(), rs.first() nothing works.
Is your problem that you do not see data in the html - if that is the case then instead of creating a new FileWriter in the CSVWriter just pass in you out variable.
Or is it that you checked the Test.csv and file and nothing is there? if so then first check to see if there is actually data in the result set by adding the following after executeQuery:
rs.last();
long numberOfRecords = rs.getRow();
rs.beforeFirst();
System.out.println("Number of Users in table is: " + numberOfRecords);
I've done listing the strings like the name etc. but I've got problem in retrieving the image. Here's my code of retrieving it. It is in the arraylist. I don't know if i'm getting the right output. Please help me. Here's my code
public ArrayList<Objects> getTaxiDetails(Connection con, String taxi_plate_no) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * from taxi_driver where taxi_plate_no = '" +taxi_plate_no+ "'");
//PreparedStatement stmt = con.prepareStatement("SELECT * from taxi_driver");
ResultSet rs = stmt.executeQuery();
try{
byte[] bytes = null;
while(rs.next()){
Objects taxiObjects = new Objects();
taxiObjects.setDriver_contact_no(rs.getString("driver_contact_no"));
taxiObjects.setDriver_name(rs.getString("driver_name"));
taxiObjects.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiObjects.setDriver_operator(rs.getString("driver_operator"));
taxiObjects.setDriver_operator_address(rs.getString("driver_operator_address"));
taxiObjects.setImage(rs.getBytes("image"));
Blob image = rs.getBlob(1);
byte[] allBytesInBlob = image.getBytes(1, (int) image.length());
taxiDetailsList.add(taxiObjects);
}
} catch (SQLException e){
e.printStackTrace();
} return taxiDetailsList;
}
Here's the output
I am getting null value when I am reading the blob data from database. What might be the issue? Can some one help me on this?
Connection con = null;
PreparedStatement psStmt = null;
ResultSet rs = null;
try {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con =
DriverManager.getConnection("jdbc:oracle:thin:#MyDatabase:1535:XE","password","password");
System.out.println("connection established"+con);
psStmt = con
.prepareStatement("Select Photo from Person where Firstname=?");
int i = 1;
psStmt.setLong(1, "Nani");
rs = null;
rs = psStmt.executeQuery();
InputStream inputStream = null;
while (rs.next()) {
inputStream = rs.getBinaryStream(1);
//Blob blob = rs.getBlob(1);
//Blob blob1 = (Blob)rs.getObject(1);
//System.out.println("blob length "+blob1);//rs.getString(1);
}
System.out.println("bytessssssss "+inputStream);//here i am getting null value.
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I believe you didn't use setString function to assign any value to firstname which leads to null
for example:
ps.preparedStatement("Select photo from person where firstname = ?");
ps.setString(1,"kick"); <----- add this line
system.out.println("bytes "+rs.getBinaryStream(1));
Another suggestions
there is no need to use rs = null; inside try catch block because you have rs=null; at beginning of
your code.
change
InputStream inputStream = null;
to
InputStream inputStream = new InputStream();
or
get rid of InputStream inputStream = null;
source you should take a look at
The most obvious error is using setLong instead of setString.
However one practice is fatal: declaring in advance. This in other languages is a good practice, but in java one should declare as close as possible.
This reduces scope, by which you would have found the error! Namely inputStream is called after a failed rs.next() - outside the loop. Maybe because no records were found.
This practice, declaring as near as feasible, also helps with try-with-resources which were used here to automatically close the statement and result set.
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:#MyDatabase:1535:XE","password","password");
System.out.println("connection established"+con);
try (PreparedStatement psStmt = con.prepareStatement(
"Select Photo from Person where Firstname=?")) {
int i = 1;
psStmt.setString(1, "Nani");
try (ResultSet rs = psStmt.executeQuery()) {
while (rs.next()) {
try (InputStream inputStream = rs.getBinaryStream(1)) {
//Blob blob = rs.getBlob(1);
//Blob blob1 = (Blob)rs.getObject(1);
//System.out.println("blob length "+blob1);//rs.getString(1);
Files.copy(inputStream, Paths.get("C:/photo-" + i + ".jpg"));
}
++i;
}
//ERROR System.out.println("bytessssssss "+inputStream);
} // Closes rs.
} // Closes psStmt.
}
1- In your code when setting the parameter's value of SQL query, be sure to use the appropriate data type of the field. So here you should use
psStmt.setString(1, "Nani");
instead of
psStmt.setLong(1, "Nani");
2- Make sure that the query is correct (Table name, field name).
3- Make sure that the table is containing data.
Currently we have a java application which have many different queries and not all are ran at one particular time. Thus for each query we plan to have a new statement and resultset and close them immediately? Below is given the snippet of code for how we run a query now.We have tried to cover each query with try and catch but the problem if the query fails them the rollback is not working on the global level. How best top put them in place to ensure no memory leak too?
try{ //main try outside
//lots of inner queries run based on some logics of if else etc
//sample query of opening and closing both statement and resultsets.
Statement stmt1 = null;
stmt1 = dbconn.createStatement();
String selectQuery1 = "Select query";
ResultSet rs1 = stmt1 .executeQuery(selectQuery1);
while(rs1.next()) {
//process here
}
try{
if (rs1 != null ){
rs1.close();
}
if (stmt1!= null ){
stmt1.close()
}
}
catch(SQLException ex){
ex.printStackTrace(System.out);
}
dbconn.commit();
}
catch (SQLException ex) {
try {
dbconn.rollback();
}
catch (Exception rollback){
rollback.printStackTrace(System.out);
}
}
catch (Exception e){
try{
dbconn.rollback();
}
catch (Exception rollback) {
rollback.printStackTrace(System.out);
}
}
For rollback to work, you have to first check whether autoCommit is set to false initially. You would want to commit only when all your operations have been executed successfully.
One way of doing this might to use a structure like this:
Connection connection = getDBConnection(); //Depends on how you get your connection
boolean autoCommit = connection.getAutoCommit();
try{
//Set autoCommit to false. You will manage commiting your transaction
connection.setAutoCommit(false);
//Perform your sql operation
if(doCommit){ //all your ops have successfully executed, you can use a flag for this
connection.commit();
}
}catch(Exception exe){
//Rollback
}finally{
connection.setAutoCommit(autoCommit); //Set autoCommit to its initial value
}
Please try keeping dbconn.setAutoCommit(false) as first statement in your first try block so that it will not insert/update/delete query unless you say dbconn.commit()
try{
conn.setAutoCommit(false);
Statement stmt1 = null;
stmt1 = dbconn.createStatement();
String selectQuery1 = "Select query";
ResultSet rs1 = stmt1 .executeQuery(selectQuery1);
while(rs1.next()) {
//process here
}
conn.commit();
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
try{
if(conn!=null)
conn.rollback();
}catch(SQLException se2){
se2.printStackTrace();
}//end try
}catch(Exception e){
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(rs!=null)
rs.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}//