Hi again. Here we see insertion of image files(here jpg file, it need not be jpg all the time, you can insert any other files also) into a MySQL database.
First create the table in the MySQL database. Issue the following SQL query to create a table by the name "Image" that stores the images which we intend.
CREATE TABLE `image` ( `id` varchar(20) NOT NULL, `size` int(11) default '0',
`image` blob NOT NULL ) ENGINE=InnoDB;
We use the "File" and "FileInputStream" class to store the parameters related to the image file and then use the method "setBinaryStream(int index, FileInputStream object, int length_of_the_file)" to insert the image into the database.
The program in java is as follows(u need to have all the JDBC drivers configured before running this java app):
Nice work...Easy to understand...
ReplyDelete@Teja:
ReplyDeleteOne should use the code inside your java class main method in JSP. I am no expert on JSP, but i know one thing you have to write the code in main inside scriptlet tags.
Also one should note that we can write
System.out.println, create a object for output stream (whatever it might be) and write to it.
like in
<%
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
File imgfile = new File("db.JPG");
//give the path to the file if the file
// is not in the same folder as the source file
FileInputStream fin = new FileInputStream(imgfile);
PreparedStatement pre =
con.prepareStatement("insert into Image values(?,?,?)");
pre.setString(1,"abc");
pre.setInt(2,3);
pre.setBinaryStream(3,fin,(int)imgfile.length());
pre.executeUpdate();
System.out.println("Successfully inserted the file into the database!");
//close the prepared statement
pre.close();
//now close the connection
con.close();
}
catch (Exception e1)
{
out.write(e1.getMessage());
}
}
%>
Hi this is Muni,
ReplyDeleteI need a code for how to retrieve image from database
with certain height and width , can u please send this code to my mail
mail:munisekhar1236@gmail.com
thanks & regards
Munisekhar
@Muni: Along with the above mentioned table add 2 columns of type "INT". Write a query to filter queries according to width and height.
ReplyDelete