图片数据的存储(数据库字段格式为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(); }