Advertisement
Guest User

Untitled

a guest
Apr 26th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.19 KB | None | 0 0
  1.  
  2. /*
  3.  
  4. Defining the Table: Oracle and MySql
  5.  
  6. create table MyPictures (
  7.    id INT PRIMARY KEY,
  8.    name VARCHAR(0),
  9.    photo BLOB
  10. );
  11. */
  12. import java.io.File;
  13. import java.io.FileInputStream;
  14. import java.io.IOException;
  15. import java.sql.Connection;
  16. import java.sql.DriverManager;
  17. import java.sql.PreparedStatement;
  18. import java.sql.SQLException;
  19.  
  20. public class InsertPictureToMySql {
  21.   public static void main(String[] args) throws Exception, IOException, SQLException {
  22.     Class.forName("org.gjt.mm.mysql.Driver");
  23.     Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "root", "root");
  24.     String INSERT_PICTURE = "insert into MyPictures(id, name, photo) values (?, ?, ?)";
  25.  
  26.     FileInputStream fis = null;
  27.     PreparedStatement ps = null;
  28.     try {
  29.       conn.setAutoCommit(false);
  30.       File file = new File("myPhoto.png");
  31.       fis = new FileInputStream(file);
  32.       ps = conn.prepareStatement(INSERT_PICTURE);
  33.       ps.setString(1, "001");
  34.       ps.setString(2, "name");
  35.       ps.setBinaryStream(3, fis, (int) file.length());
  36.       ps.executeUpdate();
  37.       conn.commit();
  38.     } finally {
  39.       ps.close();
  40.       fis.close();
  41.     }
  42.   }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement