static String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; static String url = "jdbc:microsoft:sqlserver://192.168.0.202:1433;DatabaseName=test"; static String user = "sa"; static String passwd = "ps"; public static void method() throws Exception { Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, user, passwd); int op = 0; // 插入 if (op == 0) { PreparedStatement ps = conn.prepareStatement("insert into tb_file values(?,?)"); ps.setString(1, "test.doc"); InputStream in = new FileInputStream("d:/test.doc"); ps.setBinaryStream(2, in, in.available()); ps.executeUpdate(); ps.close(); } else { // 取出 PreparedStatement ps = conn.prepareStatement("select * from tb_file where filename = ?"); ps.setString(1, "aaa.exe"); ResultSet rs = ps.executeQuery(); rs.next(); InputStream in = rs.getBinaryStream("filecontent"); System.out.println(in.available()); FileOutputStream out = new FileOutputStream("d:/test.doc"); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b)) != -1) { out.write(b, 0, len); out.flush(); } out.close(); in.close(); rs.close(); ps.close(); } } catch (Exception ex) { ex.printStackTrace(System.out); } finally { if (null != conn) conn.close(); } }
?