`
jy00509336
  • 浏览: 239400 次
  • 性别: Icon_minigender_1
  • 来自: 山西
社区版块
存档分类
最新评论

往Blob类型字段插入图片-Java源码

阅读更多

  1. /*  
  2.  
  3. Defining the Table: Oracle and MySql  
  4.  
  5. create table MyPictures (  
  6.    id INT PRIMARY KEY,  
  7.    name VARCHAR(0),  
  8.    photo BLOB  
  9. );  
  10. */  
  11. import java.io.File;   
  12. import java.io.FileInputStream;   
  13. import java.io.IOException;   
  14. import java.sql.Connection;   
  15. import java.sql.DriverManager;   
  16. import java.sql.PreparedStatement;   
  17. import java.sql.SQLException;   
  18.   
  19. public class InsertPictureToMySql {   
  20.   public static void main(String[] args) throws Exception, IOException, SQLException {   
  21.     Class.forName("org.gjt.mm.mysql.Driver");   
  22.     Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName""root""root");   
  23.     String INSERT_PICTURE = "insert into MyPictures(id, name, photo) values (?, ?, ?)";   
  24.   
  25.     FileInputStream fis = null;   
  26.     PreparedStatement ps = null;   
  27.     try {   
  28.       conn.setAutoCommit(false);   
  29.       File file = new File("myPhoto.png");   
  30.       fis = new FileInputStream(file);   
  31.       ps = conn.prepareStatement(INSERT_PICTURE);   
  32.       ps.setString(1"001");   
  33.       ps.setString(2"name");   
  34.       ps.setBinaryStream(3, fis, (int) file.length());   
  35.       ps.executeUpdate();   
  36.       conn.commit();   
  37.     } finally {   
  38.       ps.close();   
  39.       fis.close();   
  40.     }   
  41.   }   
  42. }   

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics