2.如何通过JDBC把已经存在数据库的图片读取出来,再通过IO流写到指定位置(2)
注:特别注意一点,在数据库中,并木有面向对象,所以并非像java一样的什么都是从0开始,数据库从1开始!
全部代码如下:
package a1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test07 {
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;DatabaseName = tongjunchao";
Connection con = DriverManager.getConnection(url,"sa","123");
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("select * from imgdemo where id=1");
byte[] bb = null;
while (rs.next()) {
bb = rs.getBytes(2);//通过列号得到
}
File file = new File("e:\\a3.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(bb);
fos.close();
rs.close();
con.close();
System.out.println("ok");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
这里就不截图了,在我的e盘下 就多了一个a2.jpg图片,可以打开的哟!(^__^) 嘻嘻