java 在MySQL中存储文件,读取文件(包括图片,word文档,excel表格,ppt,zip文件等)

  在设计到数据库的开发中,难免要将图片或文档文件(如word)插入到数据库中的情况。一般来说,我们可以通过插入文件相应的存储路径,而不是文件本身,来避免直接向数据库里插入的麻烦。但有些时候,直接向MySQL中插入文件,更加安全,而且更加容易管理。
  首先,先要在数据库中建表。我在名为test的数据库下建立了一个叫pic的表。该表包括3列,id, caption和img。其中id是主键,caption是对图片的表述,img是图像文件本身。建表的SQL语句如下:
DROP TABLE IF EXISTS `test`.`pic`;
CREATE TABLE `test`.`pic` (
 `id` int(11) NOT NULL auto_increment,
 `caption` varchar(45) NOT NULL default '',
 `img` longblob NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  其次,在java中对文件(如图片,word文档等)的处理,其中包括把文件存储到数据库和从数据库中读取文件。(注:storeImg()和readImg()是可以处理任意文件类型的,不仅仅是图片)
</pre><pre name="code" class="sql">  在数据库里存储文件以及从数据库读取文件的完整代码如下:
<pre name="code" class="java">import java.io.*;
import java.sql.*;
public class StoreFile {
	
    private String dbDriver;
    private String dbURL;
    private String dbUser;
    private String dbPassword;
    private Connection con;
    private PreparedStatement ps;  
    /**
   	 * 构造函数,初始化数据库的连接
   	 * 
   	 */
    public StoreFile() {
        dbDriver = "com.mysql.jdbc.Driver";
        dbURL = "jdbc:mysql://localhost:3306/test";
        dbUser = "root";
        dbPassword = "justdoit";
        initDB();
    }  
    public StoreFile(String strDriver, String strURL,
            String strUser, String strPwd) {
        dbDriver = strDriver;
        dbURL = strURL;
        dbUser = strUser;
        dbPassword = strPwd;
        initDB();
    }
 
    public void initDB() {
        try {
            // Load Driver
            Class.forName(dbDriver).newInstance();
            // Get connection
            con = DriverManager.getConnection(dbURL,
                    dbUser, dbPassword);           
        } catch(ClassNotFoundException e) {
            System.out.println(e.getMessage());
        } catch(SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
 
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    /**
	 * 将指定路径的文件(比如:图片,word文档等)存储到数据库
	 * @param strFile 要存放到数据库的文件路径,如D:\\a.jpg
	 */
    public void storeImg(String strFile) throws Exception {
            int id = 0;
            File file = new File(strFile);
            FileInputStream fis = new FileInputStream(file);           
            try {              
                ps = con.prepareStatement("insert "
                        + "into PIC values (?,?,?)");
                ps.setInt(1, id);
                ps.setString(2, file.getName());
                ps.setBinaryStream(3, fis, (int) file.length());
                ps.executeUpdate();  
                System.out.println("file insert success ");
            } catch (SQLException e) {
                System.out.println("SQLException: "
                        + e.getMessage());
                System.out.println("SQLState: "
                        + e.getSQLState());
                System.out.println("VendorError: "
                        + e.getErrorCode());
                e.printStackTrace();
            } finally {            
                ps.close();
                fis.close();
                con.close();
            }       
    }
    /**
	 * 将存储在数据库中的文件(比如:图片,word文档等)读取到指定路径
	 * @param path  从数据库里读取出来的文件存放路径 如D:\\a.jpg
	 * @param id    数据库里记录的id
	 */
    public void readImg(String path, int id) throws Exception{
    	initDB();   //建立与数据库的连接
    	byte[] buffer = new byte[4096];
    	FileOutputStream outputImage = null;
    	InputStream is = null;
    	try {
    	    ps = con.prepareStatement("select img from pic where id =?");
    	    ps.setInt(1, id);
    	    ResultSet rs = ps.executeQuery();
    	    rs.next();
    	    File file = new File(path);
    	    if (!file.exists()) {
    	      file.createNewFile();   	    
    	    }
    	    outputImage = new FileOutputStream(file);    	       	    	
    	    Blob blob = rs.getBlob("img");   //img为数据库存放图片字段名称
    	    is = blob.getBinaryStream();    	   
    	    int size = 0; 	   
    	    while ((size = is.read(buffer)) != -1) {  	     
    	    	outputImage.write(buffer, 0, size);   	     
    	    }
    	    System.out.println("file read success ");
    	} catch (Exception e) {
    		   e.printStackTrace();
    	   } finally {
    	     is.close();
    	     outputImage.close();
    	     ps.close();
    	     con.close();
    	   }
    	}
   
    public static void main(String[] args) throws Exception {
        StoreFile sp = new StoreFile();
        String imgPath="C:\\Users\\Administrator\\Pictures\\img12.jpg";
        //String wordPath="d:\\测试文档.docx";
        sp.storeImg(imgPath);
        //sp.storeImg(wordPath);
        //sp.readImg("D://数据库.jpg", 1);  //这里的1为要传入的参数:读取文件的id
        //sp.readImg("D://数据库.docx", 8);
    }
}



                
可以使用Apache POI和JDBC来实现将Excel文件存储MySQL数据库。 首先,需要在项目引入Apache POI和JDBC的依赖包。然后,可以使用POI读取Excel文件的数据,将其存储到一个Java对象,再使用JDBC将Java对象的数据存储MySQL数据库。 下面是一个简单的示例代码: ```java import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelToMysql { public static void main(String[] args) { String jdbcUrl = "jdbc:mysql://localhost:3306/test?useSSL=false"; String username = "root"; String password = "123456"; String excelFilePath = "path/to/excel/file.xlsx"; String tableName = "table_name"; try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password); FileInputStream inputStream = new FileInputStream(excelFilePath); Workbook workbook = new XSSFWorkbook(inputStream)) { Sheet sheet = workbook.getSheetAt(0); Row firstRow = sheet.getRow(0); StringBuilder sb = new StringBuilder("INSERT INTO " + tableName + " ("); for (int i = 0; i < firstRow.getLastCellNum(); i++) { Cell cell = firstRow.getCell(i); sb.append(cell.getStringCellValue()); if (i != firstRow.getLastCellNum() - 1) { sb.append(", "); } } sb.append(") VALUES ("); String query = sb.toString(); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); sb = new StringBuilder(query); for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = row.getCell(j); switch (cell.getCellType()) { case STRING: sb.append("'" + cell.getStringCellValue() + "'"); break; case NUMERIC: sb.append(cell.getNumericCellValue()); break; case BOOLEAN: sb.append(cell.getBooleanCellValue()); break; default: sb.append("null"); break; } if (j != row.getLastCellNum() - 1) { sb.append(", "); } } sb.append(")"); PreparedStatement statement = connection.prepareStatement(sb.toString()); statement.executeUpdate(); } System.out.println("Data has been inserted into table " + tableName + "."); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的示例代码,首先需要设置MySQL数据库的连接信息、Excel文件的路径和需要存储MySQL数据库的表名。然后,使用FileInputStream和XSSFWorkbook读取Excel文件的数据。 接着,通过调用Workbook对象的getSheetAt方法获取Excel文件的第一个Sheet对象,再通过调用Sheet对象的getRow方法获取每一行的数据。使用StringBuilder来构建SQL语句,最后执行PreparedStatement对象的executeUpdate方法将数据插入到MySQL数据库。 需要注意的是,上述示例代码的数据类型判断比较简单,如果Excel文件包含了日期等特殊格式的数据,还需要做相应的处理。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值