java把图片写入mysql数据库的代码

来源:互联网 发布:voa软件下载 编辑:程序博客网 时间:2024/05/21 06:43

首先,建立数据库(主意image的数据类型):
CREATE TABLE image (            
              id int(5) NOT NULL, 
              name varchar(25) default NULL,      
              photo blob,                         
PRIMARY KEY (`id`)
);

以下是Java Code:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "root", "root");
    String INSERT_PICTURE = "insert into image (id, name, photo) values (?, ?, ?)";

    FileInputStream fis = null;
    PreparedStatement ps = null;
    try {
      conn.setAutoCommit(false);
      File file = new File("myPhoto.png");
      fis = new FileInputStream(file);
      ps = conn.prepareStatement(INSERT_PICTURE);
      ps.setString(1, "001");
      ps.setString(2, "name");
      ps.setBinaryStream(3, fis, (int) file.length());
      ps.executeUpdate();
      conn.commit();
    } finally {
      ps.close();
      fis.close();
    }
  }
0 0
原创粉丝点击