SQL Server 对 Image字段进行操作
将图片写入数据库
public void testUploadPicture() {
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://192.168.0.108:1433;databasename=music";
String user = "sa";
String password = "mmiku";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException ->" + e);
}
try {
Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement ps = conn
.prepareStatement("update webdb_prod_song set song_picture=? where song_id=12313");
// ps.setString(1, "123.jpg");
InputStream input = new FileInputStream("D:\\123.jpg");
ps.setBinaryStream(1, input, input.available());
ps.executeUpdate();
ps.close();
// 取出图片
ps = conn
.prepareStatement("select * from webdb_prod_song where song_id = ?");
ps.setString(1, "12313");
ResultSet rs = ps.executeQuery();
rs.next();
InputStream in = rs.getBinaryStream("song_picture");
System.out.println(in.available());
FileOutputStream out = new FileOutputStream("D:\\12.jpg");
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 (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
---------------------------------------------------------------------------------------------------------------------------------
copyright:http://www.cnblogs.com/anee/