Can't add image to mysql database - java

I want to add an image to the database.But nothing happens.There is a connection to the database.
AssetManager assManager = getApplicationContext().getAssets();
AssetFileDescriptor assetFileDescriptor = assManager.openFd("k.jpeg");
FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor();
String newPath = path.toString();
Bitmap bitmap = BitmapFactory.decodeStream(ims);
imageView.setImageBitmap(bitmap);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
byte[] bytesImage = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(bytesImage, Base64.DEFAULT);
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO photo(id) VALUES (?)");
FileInputStream fin = new FileInputStream(fileDescriptor);
preparedStatement.setBinaryStream(1, fin);
//Executing the statement
preparedStatement.executeUpdate()
writes an error
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect string value: '\xC5\x01\xB4\xBF\x0D\x00...' for column 'id' at row

maybe you forget to set connection.
if your connection that's real have not been made.
You can connect to a database using the getConnection() method of the DriverManager class.
Connect to the MySQL database by passing the MySQL URL which is jdbc:mysql://localhost/sampleDB (where sampleDB is the database name), username and password as parameters to the getConnection() method.
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password")
semoga code ini bisa membantu anda

Related

Trying to insert image/xml file as blob in cassandra database

Actually I need to insert xml file in cassandra database. So initially am trying to insert image as a blob content later I change the code to insert xml but am facing issues in insert and retrieve the blob content as image. Can anyone suggest which is the best practice to insert image/xml file in cassandra database.
FileInputStream fis=new FileInputStream("C:/Users/anand.png");
byte[] b= new byte[fis.available()+1];
int length=b.length;
fis.read(b);
System.out.println(length);
ByteBuffer buffer =ByteBuffer.wrap(b);
PreparedStatement ps = session.prepare("insert into usersimage (firstname,lastname,age,email,city,length,image) values(?,?,?,?,?,?,?)");
BoundStatement boundStatement = new BoundStatement(ps);
int age=22;
//System.out.println(buffer);
session.execute( boundStatement.bind( "xxx","D",age,"xxx#gmail.com","xxx",length,buffer));
//session.execute( boundStatement.bind( buffer, "Andy", length));
PreparedStatement ps1 = session.prepare("select * from usersimage where email =?");
BoundStatement boundStatement1 = new BoundStatement(ps1);
ResultSet rs =session.execute(boundStatement1.bind("ramya1#gmail.com"));
ByteBuffer bImage=null;
for (Row row : rs) {
bImage = row.getBytes("image") ;
length=row.getInt("length");
}
byte image[]= new byte[length];
image=Bytes.getArray(bImage);
HttpServletResponse response = null;
#SuppressWarnings("null")
OutputStream out = response.getOutputStream();
response.setContentType("image/png");
response.setContentLength(image.length);
out.write(image);
Am facing issues while retrieving the blob content as image. could anyone please help me on this.
You are inserting data to an email and selecting from another;
A better way to read the bytes of an image would be:
BufferedImage originalImage = ImageIO.read(new File("C:/Users/anand.png"));
ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
ImageIO.write(originalImage, "png", imageStream );
imageStream.flush();
byte[] imageInByte = imageStream.toByteArray();

Trying to insert Base64 image to sql server database

//Convert binary image file to byte array to base64 encoded string
FileInputStream mFileInputStream = new FileInputStream("C:\\basicsworkspace\\base64upload\\src\\main\\resources\\basic.png");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead = 0;
while ((bytesRead = mFileInputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] ba = bos.toByteArray();
byte[] encoded = Base64.getEncoder().encode(ba);
connection = DriverManager.getConnection(connectionString);
String insertSql = "INSERT INTO test (image) VALUES "
+ "("+encoded+")";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(
insertSql);
System.out.println(prepsInsertProduct.execute());
Trying to insert image to sql server and need to have the image as base64 format. I am getting below exception. Please let me know what type of datatype and how to insert image as base64 in sql server.
Output :
INSERT INTO test (image) VALUES ([B#7229724f)
java.sql.SQLException: Invalid SQL statement or JDBC escape, terminating ']' not found.
at net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:1270)
at net.sourceforge.jtds.jdbc.SQLParser.parse(SQLParser.java:165)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.<init>(JtdsPreparedStatement.java:111)
at net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2492)
at net.sourceforge.jtds.jdbc.JtdsConnection.prepareStatement(JtdsConnection.java:2450)
at base64upload.base64upload.App.main(App.java:70)
You are just concatenating string with toString() value of byte array. That's incorrect. You should use another approach:
String insertSql = "INSERT INTO test (image) VALUES (?)";
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(insertSql);
// here set your array
prepsInsertProduct.setBytes(encoded);

Image to ByteArray to BLOB and BLOB to ByteArray to Image Conversion Issues in Java

After a lot of learning on ByteArrays & BLOBS, I managed to write the below Java code to write an image into Access DB (Using ucanaccess) and writing it back to Disk.
When I write an image back to disk the image is in incorrect format or something is messed up that you cannot open that image.
I understand it is not a good practice to store Images on DB but, this is only for my learning.
public static void Update_to_DB() throws SQLException, IOException {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
Connection conn = DriverManager.getConnection(URL);
//Statement stmt = conn.createStatement();
PreparedStatement p;
File ImgPath = new File("C:\\Users\\bharat.nanwani\\Desktop\\Desert.jpg");
BufferedImage bufferedimage = ImageIO.read(ImgPath);
WritableRaster raster = bufferedimage.getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] bytearray = date.getdata();
String query = "INSERT INTO Images(data) VALUES(?);";
p = conn.prepareStatement(query);
p.setBinaryStream(1, new ByteArrayInputStream(bytearray),bytearray.length);
p.execute();
}
public static void update_to_DISK() throws SQLException, IOException {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
Connection conn = DriverManager.getConnection(URL);
PreparedStatement p;
ResultSet rs;
String query = "SELECT Data FROM Images";
p=conn.prepareStatement(query);
rs = p.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob("Data");
byte[] bytearray = blob.getBytes(1L, (int)blob.length());
FileOutputStream fos = new FileOutputStream("C:\\Users\\bharat.nanwani\\Desktop\\New Folder\\test.jpg");
fos.write(bytearray);
fos.close();
System.out.println(bytearray);
}
}
Firstly, you should separate this into two parts:
Storing binary data in a database and retrieving it
Loading an image file and saving it again
There's no need to use a database to test the second part - you should diagnose the issues by loading the image and saving straight to a file, skipping the database.
No, I believe the problem is that you're copying the data from the WritableRaster's databuffer, and then saving that to a .jpg file. It's not a jpeg at that point - it's whatever the internal format of the WritableRaster uses.
If you want a jpeg file, you don't need to use ImageIO at all - because you've started off with a jpeg file. If you want to start and end with the same image, just copy the file (or save the file to the database, in your case). That's just treating the file as bytes.
If you need to do something like saving in a different format, or at a different size, etc, then you should ask the ImageIO libraries to save the image as a JPEG again, re-encoding it... and then store the result as a file or in the database etc.
read the image file using FileInputStream rather than WritableRaster
and then store Image file in database using setBinaryStream() method of PreparedStatement..
it will store the file in bytes.
also while getting file back from database use getBytes() method of ResultSet and store it using FileOutputStream
public static void Update_to_DB() throws SQLException, IOException {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
Connection conn = DriverManager.getConnection(URL);
//Statement stmt = conn.createStatement();
PreparedStatement p;
File ImgPath = new File("C:\\Users\\bharat.nanwani\\Desktop\\Desert.jpg");
FileInputStream fin = new FileInputStream(ImgPath);
String query = "INSERT INTO Images(Data) VALUES(?);";
p = conn.prepareStatement(query);
p.setBinaryStream(1, fin);
p.execute();
}
public static void update_to_DISK() throws SQLException, IOException {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
Connection conn = DriverManager.getConnection(URL);
PreparedStatement p;
ResultSet rs;
String query = "SELECT Data FROM Images";
p = conn.prepareStatement(query);
rs = p.executeQuery();
if (rs.next()) {
byte[] bytearray = rs.getBytes("Data");
FileOutputStream fos = new FileOutputStream("C:\\Users\\bharat.nanwani\\Desktop\\New Folder\\test.jpg");
fos.write(bytearray);
fos.close();
System.out.println(bytearray);
}
}
it will solve your problem..
Below is what I'm doing to write to DB -
public static void main(String[] Args) throws SQLException, IOException {
String URL = "jdbc:ucanaccess://C:\\Users\\bharat.nanwani\\Desktop\\Images.accdb";
Connection conn = DriverManager.getConnection(URL);
PreparedStatement p;
File ImgPath = new File("C:\\Users\\bharat.nanwani\\Desktop\\Desert.jpg");
FileInputStream fileinput = new FileInputStream(ImgPath);
byte[] bytearray = new byte[(int)ImgPath.length()];
String query = "INSERT INTO Images(data) VALUES(?);";
p = conn.prepareStatement(query);
//p.setBinaryStream(1, new ByteArrayInputStream(bytearray),bytearray.length);
p.setBytes(1, bytearray);
p.execute();
}

How to add a photo to mysql from java?

I've created a software using netbeans. now I want to add pictures to my database. I have created a table and changed the type as 'BLOB'. But, IDK how to code in java to do this.
with this, I get a image and set it to a jLabel.
now how to save this photo in mysql?
try {
lbl_imge1.setIcon(null);
jFileChooser1.showOpenDialog(this);
BufferedImage upload = ImageIO.read(jFileChooser1.getSelectedFile());
java.awt.Image photo = upload.getScaledInstance(lbl_imge1.getWidth(), lbl_imge1.getHeight(), java.awt.Image.SCALE_SMOOTH);
lbl_imge1.setIcon(new ImageIcon(photo));
} catch (Exception e) {
e.printStackTrace();
}
Now I am here,
try {
jLabel1.setIcon(null);
jFileChooser1.showOpenDialog(this);
BufferedImage upload = ImageIO.read(jFileChooser1.getSelectedFile());
java.awt.Image photo = upload.getScaledInstance(jLabel1.getWidth(), jLabel1.getHeight(), java.awt.Image.SCALE_SMOOTH);
jLabel1.setIcon(new ImageIcon(photo));
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/crazy", "root", "123");
BufferedImage buffered = ImageIO.read(jFileChooser1.getSelectedFile());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffered, "jpg", baos);
byte[] imageInByte = baos.toByteArray();
Blob blob = con.createBlob();
blob.setBytes(1, imageInByte);
String query="INSERT INTO image VALUES ('"+jTextField1.getText()+"','"+blob+"')";
PreparedStatement statement=con.prepareStatement(query);
Take your BufferedImage
BufferedImage buffered= ImageIO.read(jFileChooser1.getSelectedFile());
Get a byte array from it (From this answer)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffered, "jpg", baos );
byte[] imageInByte = baos.toByteArray();
Save byte array as blob (From this answer) (probably use a Prepared Statement)
Blob blob = connection.createBlob();
blob.setBytes(1, imageInByte);
UPDATE: connection is your database connector i.e:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
You can save any byte array to a blob column. I know that this is possible with Oracle and this also should work with MySql. Here is a small example how to do a insert with java code:
String sql = "insert into yourtable(id,binaryImage) values (?,?)";
PreparedStatement pstmt =dbConnection.prepareStatement(sql);
ByteArrayInputStream bais = new ByteArrayInputStream(your_byte_array);
pstmt.setString(1, "your_id");
pstmt.setBinaryStream(2, bais);
pstmt.execute();
pstmt.close();

How to save and load an image to a mysql database in Java?

How do you save and load an image from a database and display it in Java? I can get the file location, but I am unsure as to how to save it as a blob in the database or display the image in a swing window. I am using a PreparedStatement to get information in and out of the database.
See this MySQL Java tutorial for examples under the sections Writing images and Reading images. In outline,
// writing
String sql = "INSERT INTO Images(Data) VALUES(?)";
PreparedStatement pst = con.prepareStatement(sql);
FileInputStream fin = new FileInputStream(myFile);
pst.setBinaryStream(1, fin, (int) myFile.length());
pst.executeUpdate();
//reading
String query = "SELECT Data FROM Images LIMIT 1";
PreparedStatement pst = con.prepareStatement(query);
ResultSet result = pst.executeQuery();
result.next();
String fileName = "src/main/resources/tree.png";
FileOutputStream fos = new FileOutputStream(fileName);
Blob blob = result.getBlob("Data");
int len = (int) blob.length();
byte[] buf = blob.getBytes(1, len);
fos.write(buf, 0, len);

Categories

Resources