/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 *//**
 *
 * @author Administrator
 */import java.io.File;import java.io.FileOutputStream;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class JdbcReadFile { public static void main(String[] args) throws ClassNotFoundException {

JdbcReadFile to = new JdbcReadFile();

String url = "jdbc:sqlserver://192.168.0.10:1433;DatabaseName=oreManageDB;user=sa;password=hj123456789-+";
String user = "sa";
String password = "123456789";


String filePath = "D://cup//";
String filetype = ".jpg";

try {

Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, user, password);
String sql = "select top 1000 picture from oreManageDB.dbo.tb_record_weigh where picture IS NOT NULL";
PreparedStatement statement = conn.prepareStatement(sql); ResultSet result = statement.executeQuery(); int a = 1; while (result.next()) {
String str = result.getString("picture");
to.saveToImgFile(str, filePath + a + filetype);
a++;
}
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
    //存储为图片
public void saveToImgFile(String src, String output) {
if (src == null || src.length() == 0) {
return;
}
try {
FileOutputStream out = new FileOutputStream(new File(output));
byte[] bytes = src.getBytes();
for (int i = 0; i < bytes.length; i += 2) {
out.write(charToInt(bytes[i]) * 16 + charToInt(bytes[i + 1]));
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
      //转换字符串
private int charToInt(byte ch) {
int val = 0;
if (ch >= 0x30 && ch <= 0x39) {
val = ch - 0x30;
} else if (ch >= 0x41 && ch <= 0x46) {
val = ch - 0x41 + 10;
}
return val;
}}