往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. }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值