【发布时间】:2020-06-18 17:45:52
【问题描述】:
我想将 ID(int)、title(varchar)、plot(varchar)、release_date(date)、target(varchar) 插入现有数据库。
这是根本没有显示数据的代码。
如何将日期类型值添加到已连接的数据库中?
else if (e.getSource() == this.insert2) {
String n = this.IDField.getInt();
String m = this.titleField.getText();
String f = this.plotField.getText();
String p = this.release_dateField.getText();
String t = this.targetField.getText();
String[] name = {"MOVIE_ID","title","plot","release_date","main_target"};
this.dt = new DefaultTableModel(name, 0);
/**try~catch*/
try{
stmt.executeUpdate("insert into DB2020_MOVIEINFO values('" + n + "', '" + m + "', '" + f + "', '" + p + "', '" + t + "')");
ResultSet rset_mv = stmt.executeQuery("SELECT * FROM DB2020_MOVIEINFO");
while (rset_mv.next()) {
Object[] data = {rset_mv.getString(1), rset_mv.getString(2), rset_mv.getString(3), rset_mv.getString(4), rset_mv.getString(5)};
dt.addRow(data);
}
}
catch(SQLException se) {
se.printStackTrace();
}
this.jt = new JTable(dt);
jt.getTableHeader().setBackground(Color.decode("#b76e79"));
jt.setSelectionBackground(Color.decode("#f7f6f0"));
this.jsp = new JScrollPane(jt);
jt.setPreferredScrollableViewportSize(new Dimension(800,600));
this.add(centerPanel,BorderLayout.CENTER);
this.centerPanel.removeAll();
this.centerPanel.updateUI();
this.centerPanel.add(jsp);
this.centerPanel.setVisible(true);
}
在 Mureinik 的建议下我应用了新代码。 (我提取了日期部分)
else if (e.getSource() == this.insert2) {
Int id = this.IDField.getInt();
String title = this.titleField.getText();
String plot = this.plotField.getText();
String target = this.targetField.getText();
String[] name = {"MOVIE_ID","title","plot","main_target"};
this.dt = new DefaultTableModel(name, 0);
/**try~catch*/
try (PreparedStatement ps =
conn.prepareStatement("insert into DB2020_MOVIEINFO values(?, ?, ?, ?)") {
ps.setInt(1, id); // id should be an int
ps.setString(2, title);
ps.setString(3, plot);
ps.setString(4, target);
}
catch(SQLException se) {
se.printStackTrace();
}
this.jt = new JTable(dt);
jt.getTableHeader().setBackground(Color.decode("#b76e79"));
jt.setSelectionBackground(Color.decode("#f7f6f0"));
this.jsp = new JScrollPane(jt);
jt.setPreferredScrollableViewportSize(new Dimension(800,600));
this.add(centerPanel,BorderLayout.CENTER);
this.centerPanel.removeAll();
this.centerPanel.updateUI();
this.centerPanel.add(jsp);
this.centerPanel.setVisible(true);
}
【问题讨论】:
-
请,请,请改用
PreparedStatement类。您可以从Connection的.prepareStatement方法创建一个。
标签: java sql jdbc sql-insert