日期:2014-05-16  浏览次数:20493 次

【MySql】文件内容写入数据库和从数据库写入文件

//写入文件到数据库
	static void insert() throws Exception
	{
		String sql ="insert into news (info) values (?)";
		Connection conn=JdbcUtilSingle.getConnection();
		
		PreparedStatement pst=conn.prepareStatement(sql);
		
		File file = new File("src/jdbc/test/day01/Jdbc01.java");
		//这里不能用字节流,需要用字符流
		//InputStream inputstream = new BufferedInputStream(new FileInputStream(file));
		Reader reader = new BufferedReader(new FileReader(file));
		
		//这里也不能再用setBinaryStream了
		//setBinaryStream(1, inputstream,(long)file.length());
		pst.setCharacterStream(1, reader, (int)file.length());
		
		int i = pst.executeUpdate();
		
		System.out.println(i);
		
		JdbcUtilSingle.free(null, pst, conn);
	}
	//读出数据库信息写入文件
	static void write() throws Exception
	{
		String sql="select * from news ";
		Connection conn=JdbcUtilSingle.getConnection();
		PreparedStatement pst=conn.prepareStatement(sql);
		ResultSet rs=pst.executeQuery();
		
		File file = new File("output.java");
		
		while(rs.next())
		{
			//Blob blob = rs.getBlob(1);
			//InputStream in = blob.getBinaryStream();
			//上面兩行的作用和下面這行相同
			//InputStream in = rs.getBinaryStream(1);
			Reader reader = rs.getCharacterStream(1);
			//OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
			Writer writer = new BufferedWriter(new FileWriter(file));
			
			//这里也要换成字符数组
			//byte buff[]= new byte[1024];
			char buff[]=new char[1034];
			
			//寫入文件
			for(int i=0;(i=reader.read(buff))>0;)
			{
				writer.write(buff, 0, i);
			}
		}
		
		JdbcUtilSingle.free(rs, pst, conn);
		
		
	}
?