I am trying to save Image at SQL-SERVER Database using procedures .I have a PROCEDURE name with input parameters but I don't have procedure syntax.
BufferedImage imm = ImageIO.read(new File("C:\\MY DATA\\Release 2\\18.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(imm, "jpg", baos );
baos.flush();
byte[] immAsBytes = baos.toByteArray();
baos.close();
con.setAutoCommit(true);
CallableStatement statement = con.prepareCall(query);
ByteArrayInputStream baisForIndex2 = new ByteArrayInputStream(immAsBytes);
ByteArrayInputStream baisForIndex3 = new ByteArrayInputStream(immAsBytes);
statement.setDate(1, sqlDate);
statement.setBinaryStream(2, baisForIndex2, immAsBytes.length);
statement.setBinaryStream(3, baisForIndex3, immAsBytes.length);
statement.executeUpdate();
Error msg: Operand type clash: nvarchar is incompatible with image.
SQLSTATE: S0002
Error code: 206
Error code: 0
What I want is compatible type of Java with IMAGE type of DB of sql-server.
When inserting a stream into a blob, the JDBC driver will read the specified length from it and will not reset the the stream when done.
In your example, you use this stream for placeholder 2, and then again for placeholder 3 and specify the entire length of the underlying byte[] each time. This way, when the driver gets to placeholder 3, the stream is exhausted, and cannot be read.
One solution could be to use two stream objects:
CallableStatement statement = con.prepareCall(query);
ByteArrayInputStream baisForIndex2 = new ByteArrayInputStream(immAsBytes);
ByteArrayInputStream baisForIndex3 = new ByteArrayInputStream(immAsBytes);
statement.setDate(1, sqlDate);
statement.setBinaryStream(2, baisForIndex2, immAsBytes.length);
statement.setBinaryStream(3, baisForIndex3, immAsBytes.length);
statement.executeUpdate();
Related
I have passed BufferedImage as argument from jsp to java with following code:
<%BufferedImage citizen = ImageIO.read(new File(add1));%>
<%BufferedImage degree=ImageIO.read(new File(deg1));%>
<%String available=com.Package1.UpdataStudentInfo.useValues(citizen, degree);%>
Here "add1" and "deg1" are the path of images.
In java page, I have written following code so that I could update those Image to database (Here, I had no image saved in db column previously, so I wanted to update those columns with no images). I have kept name of variables same in argument; i.e. BufferedImage citizen of jsp is BufferedImage citizen in java and BufferedImage degree of jsp is BufferedImage degree in java as well. So there is no problem in variable name.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
try{
ByteArrayOutputStream os1 = new ByteArrayOutputStream();
ImageIO.write(citizen, "PNG", os1);
ByteArrayInputStream citizen_is = new ByteArrayInputStream(os1.toByteArray());
ByteArrayOutputStream os2 = new ByteArrayOutputStream();
ImageIO.write(degree, "PNG", os2);
ByteArrayInputStream degree_is = new ByteArrayInputStream(os2.toByteArray());
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","");
PreparedStatement stmt=con.prepareStatement("UPDATE student SET citizenship=?, degree=? WHERE sn=? ");
stmt.setBlob(1, (Blob) citizen_is);
stmt.setBlob(2, (Blob) degree_is);
stmt.setInt(3, p);
int x=stmt.executeUpdate();
con.close();
}
I have catch statement as well to handle exception. But there is no any exception, no any runtime error and compile time error. But the image is not getting stored in the database.
Please, help me to store these two image in mysql database.
String updateSQL = "UPDATE student SET citizenship=?, degree=? WHERE sn=? ";
File os1 = new File(filenameImageCitizenShip); //load image as file
File os2 = new File(filenameImageDegree); //load image as file
FileInputStream inputOs1 = new FileInputStream(os1);
FileInputStream inputOs2 = new FIleInputStream(os2);
try{
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/crm","root","");
PreparedStatement pstmt = conn.prepareStatement(updateSQL);
pstmt.setBinaryStream(1,os1);
pstmt.setBinaryStream(2,os2);
pstmt.setBinaryStream(3,p);
pstmt.executeUpdate();
}catch(Exception e){
}
I am fetching image data from a hive which is stored as binary data like
by using an InputStream object. The problem is when I am trying to encode the image, it's getting encoded but again when I am trying to decode the same encoded image it's throwing an error.
My program looks like this:
File file=new File("path");
java.io.InputStream in = rs1.getBinaryStream("entity_image");
OutputStream f = new FileOutputStream(file);
int c=0;
while((c=in.read())>-1)
{
//System.out.println(c);
f.write(c);
}
byte[] imageBytes = new byte[(int)file.length()];
in.read(imageBytes, 0, imageBytes.length);
in.close();
String imageStr = encodeImage(imageBytes);//method that returns the encoded base64 String.
byte[] imageByteArray = decodeImage(imgstring);//method returning byte []
f.write(imageByteArray);//writing the decoded image to the file
The new image file is saying that it contains error while opening?
Are there any other ways available for fetching the image data from the hive?
I checked with getbytes() method, but it says the method is not supported.
I'm working on a database application in which I'm inserting images into a database. I'm storing the InputStreams in the database as a BLOB, and I am having issues retrieving them and setting them to an ImageIcon.
try{
// Return a resultset That contains
// the photos from the hashtags the user is following.
preparedStatement = conn.prepareStatement("SELECT * FROM PHOTOS WHERE CARID=?");
preparedStatement.setInt(1, 1);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
newPhoto = new Photo(resultSet.getInt(1), resultSet.getInt(2),
resultSet.getLong(3), resultSet.getBinaryStream(4));
System.out.println(resultSet.getBinaryStream(4));
photos.add(newPhoto);
System.out.println("Retrieving a photo");
}
}
photos is an ArrayList using my Photo class, which I am returning. Every time I try to display the images, I am getting the following error...
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at business.appdev.Home.paintEditFrame(Home.java:577)
which is coming from the following code..
editImageLabel[i].setIcon(
new ImageIcon(img.getScaledInstance(imageSize, imageSize, imageSize)));
I have some basic println commands that are showing me what's returning from the MySQL database, which is
java.io.ByteArrayInputStream#2c0213a5
Retrieving a photo
java.io.ByteArrayInputStream#252ab7be
Retrieving a photo
where img is a BufferedImage. Any help would be greatly appreciated, Thanks!
Code for handling of the InputStream returned from the resultSet
for(int i = 0; i < photos.size(); i++){
img = ImageIO.read(photos.get(i).getInputStream());
editImageLabel[i] = new JLabel("");
editImageLabel[i].setIcon(new ImageIcon(img.getScaledInstance(imageSize, imageSize, imageSize)));
updated Photo class with byte[] data
Based on some other posts I've read, I'm storing the byte[] into a varbinary in MySQL. After that, I grab the photo data from my database using
InputStream in = resultSet.getBinaryStream(4);
byte[] photoData = new byte[(int) resultSet.getLong(3)];
ByteArrayOutputStream os = new ByteArrayOutputStream();
for (int len; (len = in.read(photoData)) != -1;)
os.write(photoData, 0, len);
os.flush();
I then create my photo object and return an ArrayList of photos. This has eliminated the NullPointerException, but I now cannot get the ImageIcon JLabels to show up. I use the following code to add them to a JPanel,
InputStream in = new ByteArrayInputStream(photos.get(i).getData());
BufferedImage newImage = ImageIO.read(in);
editImageLabel[i] = new JLabel("");
editImageLabel[i].setIcon(new ImageIcon(newImage.getScaledInstance(imageSize, imageSize, Image.SCALE_DEFAULT)));
and then I place the Label onto the JPanel.
Avoid the trouble of encoding and decoding images by storing the image in the filesystem and just the path to the image in your database. This can help to keep your database size down which, in turn, can help your transactional efficiency. You can write up some quick code to make a numeric filename for the file on your server.
Basically I have to save an image I put on a JLabel on my DB(I have a BLOB var there)
JLabel LImg = new JLabel();
ImageIcon img = new ImageIcon("**filepath**");
LImg.setIcon(img);
stmt.executeUpdate("INSERT INTO CLIENT(ID, IMAGE) VALUES (1,"+LImg.getIcon()+")");
After running a few tests, I found out the getIcon method returns the file path, which explains this error
GDS Exception. 335544569. Dynamic SQL Error
SQL error code = -104
Token unknown - line 1, column 132
:
Please, be especific on your answer(I'm new on JAVA)
You cannot paste the image itself into a SQL statement. You need to use a parameterized prepared statement, and set the value being inserted as a byte array:
BufferedImage bi = (BufferedImage)LImg.getImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, type, baos);
byte[] dataToWrite = baos.toByteArray();
PreparedStatement stmt = con.prepareStatement("INSERT INTO CLIENT(ID, IMAGE) VALUES (1,?)");
stmt.setBlob(1, dataToWrite);
stmt.executeUpdate();
I have an Array of java.lang.Bytes[] in Android and I want to save it to a SQLLite table into a BLOB column.
I created the table and columns etc. I am unsure of how to save the Array as a BLOB as is.
public void AddUpdateKeys(int deviceID, String key, Boolean learned, Byte[] rawKey)
{
... // other code
ContentValues cv = new ContentValues();
cv.put(colKeyDevID, deviceID);
cv.put(colKeyLearned, key);
cv.put(colKeyLearned, learned ? 1 : 0 );
cv.put(colKeyData, rawKey); <-- Here is the issue, how to convert Type Byte[] to byte[]
How do I convert the Raw data that is in java.lang.Byte[] to byte[], I have tried
private byte[] getBytes(Byte[] learnedKey) {
byte[] result = new byte[learnedKey.length];
for(int i=0; i<learnedKey.length; i++){
result[i] = learnedKey[i].byteValue();
}
return result;
}
But is just "crashes", I also checked the the rawKey contains data? I am new to Android SQLLite Java. I want to Save the raw data of Byte[] into a Blob and read it back later and use it again.
actually An SQL BLOB type stores a large array of binary data (bytes) as the value in a column of a database.
so use column value type should specified as blob over table.and then save your byte[] into that.you should have to follow these steps over there(exm. image):
1-convert image to bitmap.
2-convert bitmap to Byte array.
public static byte[] getBytesFromBitmap(Bitmap bitmap) {
if (bitmap!=null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
return null;
}
3-make column type as blob.
4-save this byte array to that column.