Reputation: 13
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
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
Reputation: 3398
I normally use the following simple technique to achieve that, which is,
Upvotes: 2