美文网首页
测试数据库存储文件的方式

测试数据库存储文件的方式

作者: zigzh | 来源:发表于2018-02-08 00:57 被阅读0次

    mysql.jar底层没有重写PreparedStatement的setBlob(index, InputStream)##

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    
    
    /**
     * 
     */
    
    /**
     * @author 17503
     *
     */
    public class Test {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            //insert(new File("H:\\Tools\\TestXML\\4.xml"));
            readAndWrite();
        }
        
        public static void readAndWrite() {
    
            try(OutputStream os = new FileOutputStream("H:\\4.xml")){
                Connection con = conn();
                PreparedStatement pst = 
                        con.prepareStatement("select img.img from img where id=1");
                ResultSet rs = pst.executeQuery();
                rs.next();
                byte[] data = rs.getBytes(1);
                os.write(data);
                
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
        
        public static void insert(File file) {
            
            try(InputStream is = new FileInputStream(file);){
                Connection con = conn();
                System.out.println(con);
                System.out.println(file.isFile());
                byte[] data = new byte[(int)file.length()];
                is.read(data);
                
                PreparedStatement pst = 
                        con.prepareStatement("insert into img values('1',?)");
                pst.setBytes(1, data);
            
                //pst.setBlob(1, is);
                
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
        
        public static Connection conn() throws Exception {
            
            try {
                return DriverManager.getConnection("jdbc:mysql:///test", "root", "etoak");
            } catch (SQLException e) {
                e.printStackTrace();
                throw new Exception("losing Connection..");
            }
        }
        static{
            try{
                Class.forName("com.mysql.jdbc.Driver");
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:测试数据库存储文件的方式

          本文链接:https://www.haomeiwen.com/subject/mqezzxtx.html