user3402751
user3402751

Reputation: 13

add a jpg file to mysql DB in java

i have a field in a mysql table that i set data type as 'BLOB'. how can i insert a jpg file into the my table in my java code? mean's how can i read a jpg file and use that in the insert expression? i use follow instructions to read the jpg file:

File fi = new File("C:\\Users\\Kamyar\\Desktop\\i.jpg");
byte[] fileContent = Files.readAllBytes(fi.toPath());

and using following code to insert into the table:

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Server1", 
"root", "admin");
Statement stmt=con.createStatement();
stmt.execute("Insert into users values( 'Salar5'  ,  '1234'  ,  'describe'  
,'" + **here** + "' ,  88 ,  99  ,  '1/1/93' );");
con.close();

i don't know how can i use the file in the insert expression. thanks...

Upvotes: 1

Views: 607

Answers (2)

CBredlow
CBredlow

Reputation: 2840

What you can do is create a PreparedStatement instead of a Statement object, and you can bind the values you need to the statement as you need them.

For blobs, one thing you can use is a binary stream.

PreparedStatement ps = con.PrepareStatement("INSERT STATEMENT");
InputStream is = new FileInputStream(fi);
ps.setBinaryStream(n, is, fileContent.length);

where n is the index in the prepared statement, which is in your case 3 if you bind every value.

Upvotes: 0

Dilukshan Mahendra
Dilukshan Mahendra

Reputation: 3398

I normally use the following simple technique to achieve that, which is,

  • uploading the file into a Fixed Folder using a file up-loader in the project folder(like defining a folder as Images) as desired
  • Save the path of the Image including image name to the database table when you upload the image, but not the actual object. (Ex: ../Project/Images/MyImage.jpg)
  • then whenever you need to display the image, you call it by the path and file name as above.

Upvotes: 2

Related Questions