import java.sql.*; import java.io.*; import com.mysql.jdbc.*; // import org.gjt.mm.mysql.*; public class BlobT { /** * insert Blob int table * * @param name * @param filename */ public void putFile(String name, String filename){ java.sql.PreparedStatement pstmt = null; java.io.File fFile = null; java.io.FileInputStream isFile = null; try{ // CREATE TABLE test.imgdata_tab(img blob, name varchar(40)); pstmt = conn.prepareStatement("INSERT INTO imgdata_tab (img,name) VALUES( ?, ? )"); fFile = new File(filename); isFile = new FileInputStream(fFile); pstmt.setBinaryStream(1, isFile, (int)(fFile.length())); pstmt.setString(2, name); pstmt.executeUpdate(); } catch (Exception e){ System.out.println("error: " + e); } } /** * make the connection */ public final void makeConnection (String encodingName) { try { String userName = "root"; String password = ""; String url = "jdbc:mysql://localhost/test"; Class.forName ("com.mysql.jdbc.Driver").newInstance (); conn = DriverManager.getConnection (url +"?user=" + userName + "&password=" + password + "&characterEncoding=" + encodingName); // conn = DriverManager.getConnection (url +"?user=" + userName + "&password=" + password); System.out.println ("Database connection established with encoding: " + encodingName); } catch (Exception e) { e.printStackTrace (); } finally { } } /** * close the connection */ public final void closeConnection () { if (conn != null) { try { conn.close (); System.out.println ("Database connection terminated"); } catch (Exception e) { /* ignore close errors */ } } } /** * main */ public static void main (String[] args) { if (args.length < 1) { System.out.println ("Usage: java BlobT insert mysql.gif logo"); System.exit (0); } final String operation = args[0]; final String fileName = args[1]; final String name = args[2]; BlobT blobT = new BlobT (); // make the connection // String encodingName = "CP932"; String encodingName = "MS932"; // String encodingName = "UTF-8"; blobT.makeConnection (encodingName); // do something if (operation.equalsIgnoreCase ("insert")) { blobT.putFile (encodingName, fileName); } else { System.out.println ("huh ???"); } // close connection blobT.closeConnection (); // get out System.exit (0); } java.sql.Connection conn = null; }