Inserting image into mySQL
Hi,
I wonder if any one might be able to help, i am trying to insert a .jpg into a mySQL data base, so far i have tried inserting the file as byte[], i keep on recieveing an error message, stating that the syntax i have used is incorrect,
is nay one able to help me? i have provided a copy of the create table SQL used as well,
Thanks in advance.
public void putFile(int FoodID, File infile){
try{
System.out.println(infile.getName());
FileInputStream is=new FileInputStream(infile);
byte[] b=new byte[(int)infile.length()];
is.read(b);
bt=b;
//is.close();
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO photo VALUES("+FoodID+",'"+infile.getName()+"',"+bt+")");
stmt.close();
con.commit();
}catch (Exception e){
System.out.println("error: " + e);
}
}
Create Table Photo(
Foodin_id INT NOT NULL,
photoName VARCHAR(150) NOT NULL,
PRIMARY KEY(Foodin_id, photoName),
photo MEDIUMBLOB NOT NULL,
Foreign Key (Foodin_id)
References Food_Inspect(Foodin_id)) TYPE=INNODB;
Blobs must be treated as streams
Check this code, it inserts an image into a mySql db like.
Here is the table definition
Code:
create table image_tab
(
image_name VARCHAR(42) not null,
image_content LONG VARBINARY ,
primary key (image_name)
);
here is the java code
Code:
import java.sql.*;
import java.io.*;
public class StoreBinary {
private static String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
private Statement stmt = null;
private Connection conn = null;
public StoreBinary() {
}
public void storeImageFile(String fileName) throws Exception {
if (!connect("test", "root", "")) {
return;
}
FileInputStream in = new FileInputStream(fileName);
int len=in.available();
PreparedStatement pStmt = conn.prepareStatement("insert into image_tab values (?,?)");
pStmt.setString(1, fileName);
pStmt.setBinaryStream(2, in, len);
pStmt.executeUpdate();
in.close();
System.out.println("Stored: "+fileName+", length: "+len);
}
public boolean connect(String dbName, String dbUser, String dbPassword) {
try {
Class.forName(driverName);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
return false;
}
try {
conn = DriverManager.getConnection("jdbc:odbc:" + dbName,
dbUser,
dbPassword);
//stmt = conn.createStatement();
}
catch (SQLException ex1) {
ex1.printStackTrace();
return false;
}
return true;
}
/**
* MAIN ***********************
*/
public static void main(String[] args) {
StoreBinary sb = new StoreBinary();
try {
sb.storeImageFile("c:\\tmp\\f128.jpg");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}