我试图以Java应用程序形式选择多个图像并将其保存在我的SQL Server中,并在单击“搜索”按钮时在jLabel中显示它们。 这些是我在“浏览”按钮中的代码:
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
filename = f.getAbsolutePath();
ImageIcon imageIcon = new ImageIcon(new ImageIcon(filename).getImage().getScaledInstance(jLabel1.getWidth(), jLabel1.getHeight(), Image.SCALE_SMOOTH));
jLabel1.setIcon(imageIcon);
File image = new File(filename);
try {
FileInputStream fis = new FileInputStream(image);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
} catch (IOException ex) {
Logger.getLogger(testJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
personImage = bos.toByteArray();
} catch (FileNotFoundException ex) {
Logger.getLogger(testJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
保存按钮:
String name = jTextField1.getText();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(testJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=test", "sa", "oraclee");
String url = "INSERT INTO imageTable (name,photo) VALUES (?,?)";
PreparedStatement ps = conn.prepareStatement(url);
ps.setString(1, name);
ps.setBytes(2, personImage);
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "saved");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "sorry,, not saved!");
}