Issue with getBinaryStream(index) - java

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.

Related

Database rows reading into list of objects

public static List<SPACE_CreateLicenseModel> SPACE_getDetails() throws ClassNotFoundException, FileNotFoundException, JSONException{
SPACE_CreateLicenseModel view = new SPACE_CreateLicenseModel();
Statement stmt = null;
Connection connect = null;
List<SPACE_CreateLicenseModel> allData = new ArrayList<SPACE_CreateLicenseModel>();
try {
connect = SPACE_DBController.SPACE_getConnection();
stmt = connect.createStatement();
JSONObject obj = SPACE_Parse.parse ("C:/Users/Rachana/workspace/SPACEOM/WebContent/Data/SPACE_Database.json");
String tablename = obj.getString("table_name");
String sql = "SELECT * FROM " + tablename + " WHERE (SPLD_LicenseActiveStatus <> 5 OR SPLD_LicenseActiveStatus IS NULL)";
ResultSet result = stmt.executeQuery(sql);
int i =0;
while (result.next()) {
view.setSPLD_DeviceID_Mfg(result.getString(1));
view.setSPLD_DeviceID_ModelNo(result.getString(2));
view.setSPLD_DeviceID_SrNo(result.getString(3));
view.setSPLD_DeviceID_Search_mode(result.getByte(4));
view.setSPLD_LicenseType(result.getByte(5));
view.setSPLD_LicenseTypeChangedDate(result.getDate(6));
view.setSPLD_LicenseActiveStatus(result.getByte(7));
view.setSPLD_LicenseActiveDate(result.getDate(8));
view.setSPLD_LicenseAccess(result.getByte(9));
view.setSPLD_LicenseAccessMaxNo(result.getInt(10));
view.setSPLD_LicenseAccessCounter(result.getInt(11));
view.setSPLD_LicenseStartDate(result.getDate(12));
view.setSPLD_LicenseExpiryDate(result.getDate(13));
view.setSPLD_LicenseeOrg(result.getString(14));
view.setSPLD_LicenseeAddress(result.getString(15));
view.setSPLD_LocationActive(result.getString(16));
view.setSPDL_Longitude(result.getDouble(17));
view.setSPDL_Latitude(result.getDouble(18));
view.setSPDL_LocationTolerance(result.getFloat(19));
view.setSPLD_FutureOption1(result.getString(20));
view.setSPLD_FutureOption2(result.getString(21));
view.setSPLD_FutureOption3(result.getString(22));
view.setSPLD_FutureOption4(result.getInt(23));
view.setSPLD_FutureOption5(result.getInt(24));
view.setSPLD_StatCounter1_FirstUseDate(result.getDate(25));
view.setSPLD_StatCounter2_MessageTotal(result.getInt(26));
view.setSPLD_StatCounter3_FailedAttempts(result.getInt(27));
view.setSPLD_StatCounter4_FirstFailedAttemptDate(result.getDate(28));
view.setSPLD_StatCounter5_LastFailedAttemptDate(result.getDate(29));
view.setSPLD_StatCounter6(result.getInt(30));
view.setSPLD_StatCounter7(result.getInt(31));
view.setSPLD_StatCounterOption1(result.getString(32));
view.setSPLD_StatCounterOption2(result.getString(33));
view.setSPLD_StatCounterOption3(result.getString(34));
view.setSPLD_StatCounterOption4(result.getInt(35));
view.setSPLD_StatCounterOption5(result.getInt(36));
view.setSPLD_MainContact1Name(result.getString(37));
view.setSPLD_MainContact2Name(result.getString(38));
view.setSPLD_MobileNo1(result.getString(39));
view.setSPLD_MobileNo2(result.getString(40));
view.setSPLD_EmailID1(result.getString(41));
view.setSPLD_EmailID2(result.getString(42));
view.setSPLD_CustomerDetailOption1(result.getString(43));
view.setSPLD_CustomerDetailOption2(result.getString(44));
view.setSPLD_BroadCastGEN1(result.getString(45));
view.setSPLD_BroadCastGEN2(result.getString(46));
view.setSPLD_BroadCastID1(result.getInt(47));
view.setSPLD_DevSpecGEN1(result.getString(48));
view.setSPLD_DevSpecGEN2(result.getString(49));
view.setSPLD_DevSpecGEN3(result.getString(50));
view.setSPLD_DevSpecID1(result.getInt(51));
view.setSPLD_DevSpecID2(result.getInt(52));
view.setSPLD_MessageStatus(result.getString(53).charAt(0));
allData.add(i,view);
i++;
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(connect!=null)
connect.close();
}catch(SQLException se){
se.printStackTrace();
}
}
return allData;
}
I am fetching all the rows of the database and storing it in array. But while displaying only the last row is getting printed. The list elements are getting overridden. i.e., allData.add(1,view), allData.add(2,view) , allData.add(3,view) , allData.add(4,view) etc everything are same.
As you are not creating a new Object for each iteration of the loop, it is re-using the same object, so try
Statement stmt = null;
Connection connect = null;
List<SPACE_CreateLicenseModel> allData = new ArrayList<SPACE_CreateLicenseModel>();
try {
connect = SPACE_DBController.SPACE_getConnection();
....
while (result.next()) {
SPACE_CreateLicenseModel view = new SPACE_CreateLicenseModel();
Cause:
Currently for each row same object is getting updated hence all your objects in list have same values (Last Row).
Resolution:
You need to initialize SPACE_CreateLicenseModel each time in loop for every row.
while (result.next()) {
SPACE_CreateLicenseModel view = new SPACE_CreateLicenseModel();
view.setSPLD_DeviceID_Mfg(result.getString(1));
.
.
allData.add(i,view);
i++;
}
Hope this helps
Create a new view object with every iteration of your while loop. Every time you loop through the same view object is getting over written in memory. The final time your loop runs it replaces it with the last row values which is being displayed when you are printing your data...
while(yourCondition){
view = new SPACE_CreateLicenseModel();
//your code goes here....
}
Adding the above line in your loop will create a new view Object and will be added to your allData variable.

Updating JLabel via SetIcon from bytea data type in postgres

I am retrieving gif images from Wolfram|Alpha. In an effort to minimize queries I want to store those images and only query W|A when the data is changed, so I am storing the images as a bytea data type in my postgres db. The "save" portion seems to be working because there is data. System.out.println(rs.getString("fnPlotImg")) yields this: \x4275666665726564496d6167654035356437373834323a2074797065203d203120446972656374436f6c6f724d6f64656c3a20726d61736b3d66663030303020676d61736b3d6666303020626d61736b3d666620616d61736b3d3020496e7465676572496e7465726c65617665645261737465723a207769647468203d2032303020686569676874203d20313335202342616e6473203d203320784f6666203d203020794f6666203d203020646174614f66667365745b305d2030
I have been able to successfully update the image from W|A using this bit of code:
String path = ((WAImage) element).getURL();
URL url = new URL(path);
BufferedImage image = ImageIO.read(url);
picLabel.setIcon(new ImageIcon(image));
I would like to update my application with the image from the database and have attempted this code:
byte[] ba = rs.getBytes("fnPlotImg");
try{
picLabel.setIcon(new ImageIcon(ba));
} catch (NullPointerException e) {
e.printStackTrace();
}
My rationale is that bytea is a byte array, getBytes() is supposed to retrieve a byte array, and ImageIcon() is supposed to handle a byte array.However, if I don't build in a null pointer exception it errors out. I presume this is because I am not saving the image to DB correctly or I am not retrieving it correctly.
All thoughts are welcome, I'm getting fatigued so I'll check in the morning with fresh eyes.
I don't have a installation of PostgreSQL available, but I think you should be writing/reading the image format and not the BufferedImage data.
For example, writing might look something like...
Connection con = ...;
BufferedImage img = ...;
try (PreparedStatement stmt = con.prepareStatement("insert into tableofimages (image) values (?)")) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write(img, "png", baos);
try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray())) {
stmt.setBinaryStream(1, bais);
int rows = stmt.executeUpdate();
System.out.println(rows + " rows updated");
}
}
} catch (SQLException | IOException exp) {
exp.printStackTrace();
}
And reading might look something like...
Connection con = ...;
try (PreparedStatement stmt = con.prepareStatement("select image from tableofimages")) {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
try (InputStream is = rs.getBinaryStream(1)) {
BufferedImage img = ImageIO.read(is);
}
}
}
} catch (SQLException | IOException exp) {
exp.printStackTrace();
}

Getting blob image in mysql using restful web service

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

How do I connect to data base from servlet. I have tried the following code, but control goes to exception everytime

How do I connect to data base from servlet. I have tried the following code, but control goes to exception everytime.
try
{
int num_rows = 0;
Connection con = null;
Statement st = null;
Statement search = null;
ResultSet rs = null;
ResultSet searchRS = null;
// Connecting to the database
PrintWriter out = response.getWriter();
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/employees","root","");
st = con.createStatement();
rs = st.executeQuery("select employees.first_name,employees.last_name,employees.gender,employees.hire_date,departments.dept_name,salaries.salary from employees,departments,salaries,dept_emp where employees.emp_no=salaries.emp_no AND dept_emp.emp_no=employees.emp_no AND dept_emp.dept_no=departments.dept_no AND salaries.to_date='9999-01-01' AND (employees.first_name='"+Sname+"' OR employees.last_name='"+Sname+"')");
//Retrieval of data from result set retrieved from database
String[][] str = new String[10][6];
while( rs.next())
{
str[num_rows][0] = rs.getString("first_name");
str[num_rows][1] = rs.getString("last_name");
str[num_rows][2] = rs.getString("gender");
str[num_rows][3] = rs.getString("hire_date");
str[num_rows][4] = rs.getString("dept_name");
str[num_rows][5] = rs.getString("salary");
num_rows++;
}
if(num_rows <10)
{
isLast = true;
var = 0;
}
request.setAttribute("listvalue",str);
request.setAttribute("rows",num_rows);
RequestDispatcher RequestDispatcherObj =request.getRequestDispatcher("SearchName.jsp");
RequestDispatcherObj.forward(request, response);
out.flush();
con.close();
var = var +10;
}
catch(Exception e)
{
e.printStackTrace();
}
Your string array can hold 10 records; probably you are getting more than that from the database.
You may try this-
while( rs.next() && num_rows < 10 )
In case you need to collect all the records, better use some collection like List.
For me looks like the line
RequestDispatcherObj.forward(request, response);
is creating the problem. It is forwarding the request to some other place. The requestdispatcheobj may have closed the out object. So after that use of flush() and write() will lead to an IllegalStateException.
out.flush();
con.close();
var = var +10;
So make sure this is not the case.

Writing Video Files in Java

I'm trying to find a way to save a video file. Initially I'd put the video files as blob data into a database, and now, I'm trying to get the blob data back, convert it into bytes, and then write it to a new file. I've been successful in doing this, but the problem is, I can't make the resulting files to run. I tried storing, retrieving, and writing .flv and .mp4 files, but neither work :/ Can anyone help me? Much appreciated! :)
Here is my code: :)
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "root","password");
Statement st1 = (Statement) con.createStatement();
PreparedStatement pstmt = null;
ResultSet rs = null;
pstmt = con.prepareStatement("SELECT video_file from video where video_id = " + video_id);
rs = pstmt.executeQuery();
Blob blob = null;
byte[] blyte = null;
if(rs.next()) {
blob = rs.getBlob("video_file");
InputStream is = blob.getBinaryStream();
FileOutputStream fos = new FileOutputStream("C:\\Downloads\\file2.mp4");
int b = 0;
while(b != -1){
fos.write(b);
b = bis.read();
}
}
//exceptions beyond this point
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
There is a '\0' byte written to fos in first iteration of the while-loop which does not come from bis.read().

Categories

Resources