This code snippet is written to
insert an image into a table. Hence, first, a table is created with the
following schema as shown below. Check that the data type of the photo
attribute, blob. The data type blob is used to hold large binary data
where the length of the data is variable.
Here, the table (photo) is created in library database.
Thus, the following code snippet is written to insert an image in this
table.
You may try the following code snippet.
package com.t4b.jdbc.mysql.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertPictureToMySql {
public static void main(String[] args) throws Exception, IOException, SQLException {
Class.forName("org.gjt.mm.mysql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "pass123");
String INSERT_PICTURE = "insert into photos(id, name, photo) values (?, ?, ?)";
FileInputStream fis = null;
PreparedStatement ps = null;
try {
conn.setAutoCommit(false);
File file = new File("photo_1.jpeg");
fis = new FileInputStream(file);
ps = conn.prepareStatement(INSERT_PICTURE);
ps.setInt(1, 1);
ps.setString(2, "photo_1.jpeg");
ps.setBinaryStream(3, fis, (int) file.length());
ps.executeUpdate();
conn.commit();
} finally {
ps.close();
fis.close();
}
}
}


No comments:
Post a Comment
Note: Only a member of this blog may post a comment.