将文件存储到数据库中(MySQL)

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();
 }

}

 

posted @ 2013-07-20 19:04  javawebsoa  Views(641)  Comments(0Edit  收藏  举报