`

文件,DB

阅读更多
package com.play;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class FileToDatabase {

 public static void main(String[] args) throws Exception {
  File file = new File("F:\\pig.jpg");
  InputStream inputStream = new FileInputStream(file);
  Class.forName("com.mysql.jdbc.Driver");
  Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
  String sql = "insert into t_user(name,image) values(?,?)";
  PreparedStatement ps = con.prepareStatement(sql);
  ps.setString(1, "wangba");
  ps.setBinaryStream(2, inputStream, (int)file.length());
  int rows = ps.executeUpdate();
  System.out.println(rows+"行受影响");
  ps.close();
  con.close();
 }

}

 

package com.play;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DatabaseToFile {

 public static void main(String[] args) throws Exception {
  Class.forName("com.mysql.jdbc.Driver");
  Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
  String sql = "select * from t_user where name=?";
  PreparedStatement ps = con.prepareStatement(sql);
  ps.setString(1, "wangba");
  ResultSet rs  = ps.executeQuery();
  while(rs.next()){
   Blob blob = rs.getBlob("image");
   OutputStream os = new FileOutputStream("D:\\a.jpg");
   os.write(blob.getBytes(1, (int)blob.length()));
   os.flush();
   os.close();
  }
  rs.close();
  ps.close();
  con.close();
 }

}

 

 

http://blog.csdn.net/machunmei2/article/details/9388765

http://blog.csdn.net/machunmei2/article/details/9389105

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics