圖片數據的存儲(數據庫字段格式爲blob) java
存數據 數據庫
Connection conn = JdbcUtils.getConnection(); //建立預處理對象 PreparedStatement pstmt = conn.prepareStatement("insert into t1 values(?,?)"); //指定問號的值 pstmt.setInt(1, 1); File file = new File("src/2.gif"); InputStream in = new FileInputStream(file); pstmt.setBinaryStream(2, in, file.length()); //執行SQL語句 pstmt.executeUpdate();
取數據 ide
Connection conn = JdbcUtils.getConnection(); //建立預處理對象 PreparedStatement pstmt = conn.prepareStatement("select * from t1"); //執行SQL語句 ResultSet rs = pstmt.executeQuery(); if(rs.next()){ int id = rs.getInt("id"); InputStream in = rs.getBinaryStream("p_w_picpath"); //須要再建一個文件 File file = new File("src/3.gif"); OutputStream os = new FileOutputStream(file); byte[] buffer = new byte[1024]; int b = 0; while((b=in.read(buffer)) != -1){ os.write(buffer,0,b); }
大文本數據的存儲(數據庫字段格式爲text) 對象
存數據 圖片
Connection conn = JdbcUtils.getConnection(); //建立預處理對象 PreparedStatement pstmt = conn.prepareStatement("insert into t2 values(?,?)"); //指定問號的值 pstmt.setInt(1, 1); File file = new File("src/a.txt"); FileReader fileReader = new FileReader(file); pstmt.setCharacterStream(2, fileReader,file.length()); //執行SQL語句 pstmt.executeUpdate();
取數據 get
Connection conn = JdbcUtils.getConnection(); //建立預處理對象 PreparedStatement pstmt = conn.prepareStatement("select * from t2"); //執行SQL語句 ResultSet rs = pstmt.executeQuery(); if(rs.next()){ int id = rs.getInt("id"); Reader reader = rs.getCharacterStream("txt"); //須要再建一個文件 File file = new File("src/b.txt"); BufferedReader br = new BufferedReader(reader); BufferedWriter bw = new BufferedWriter(new FileWriter(file)); String s = ""; while((s = br.readLine()) != null){ bw.write(s); bw.write("\r\n"); } br.close(); bw.close(); }