我想使用Java将图像保存到我的sql服务器数据库中。我正在使用NetBeans IDE,选择图片并单击“保存”按钮时,我的数据库字段(图片)显示了NULL
的值。
这些是我的代码:
Connection conn = null;
PreparedStatement ps = null;
String url = "jdbc:sqlserver://localhost:1433;databaseName=test";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(JFrameMain.class.getName()).log(Level.SEVERE, null, ex);
}
try {
conn = DriverManager.getConnection(url, "sa", "oraclee");
} catch (SQLException ex) {
Logger.getLogger(JFrameMain.class.getName()).log(Level.SEVERE, null, ex);
}
try {
ps = conn.prepareStatement(" INSERT INTO imageTable (photo) values (?)");
} catch (SQLException ex) {
Logger.getLogger(JFrameMain.class.getName()).log(Level.SEVERE, null, ex);
}
try {
ps.setBytes(1, photo);
} catch (SQLException ex) {
Logger.getLogger(JFrameMain.class.getName()).log(Level.SEVERE, null, ex);
}
try {
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "done..!!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "sorry, n't saved");
}
答案 0 :(得分:0)
完成.. !!!
错误在“保存”按钮代码中 这些是最终的代码:
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, "n't saved");
}
但是,首先,我们应该在程序的开头添加此行,以定义 personImage :
public class testJFrame extends javax.swing.JFrame {
byte[] personImage = null;