图片数据的存储(数据库字段格式为blob)
存数据
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();
取数据
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("image"); //需要再建一个文件 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();
取数据
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(" "); } br.close(); bw.close(); }
本文出自 “曾颐楠的播客” 博客,请务必保留此出处http://zengyinan.blog.51cto.com/9524976/1721403