NetBeans是我的Java编程编辑器。我编写了以下JDBC Prepared Statements代码。代码编译得很好,但是当我运行它时会产生错误。我检查了所有的Java书籍;没有关于使用NetBeans来编写使用JDBC准备语句的应用程序的示例我需要帮助。
以下是代码:
private void editButtonActionPerformed(java.awt.event.ActionEvent evt)
{
String sql = "Update Products SET"
+ "Description = ?, "
+ "Price = ? "
+ "Where Code = ?";
try
{
pstmt.setString(1, "CODE");
pstmt.setString(2, "DESCRIPTION");
pstmt.setDouble(3, Double.parseDouble("PRICE"));
int rowUpdated = pstmt.executeUpdate();
if (rowUpdated > 0)
{
JOptionPane.showMessageDialog(null,
"record updated successfully");
}
// Clean-up environment
rs.close();
pstmt.close();
con.close();
} catch (SQLException e)
{
JOptionPane.showMessageDialog(Product.this, e.getMessage());
}
}
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt)
{
}
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt)
{
}
private void acceptButtonActionPerformed(java.awt.event.ActionEvent evt)
{
try
{
String sql = "Insert into PRODUCTS(CODE, DESCRIPTION, PRICE)"
+ "Values(?, ?, ?)";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, codeTextField.getText());
pstmt.setString(2, descriptionTextField.getText());
pstmt.setDouble(3, Double.parseDouble("Price"));
int rowInserted = pstmt.executeUpdate();
if (rowInserted > 0)
{
JOptionPane.showMessageDialog(
null, "A new user was inserted successfully!");
}
// Clean-up environment
rs.close();
pstmt.close();
con.close();
} catch (SQLException e)
{
JOptionPane.showMessageDialog(Product.this, e.getMessage());
}
}
答案 0 :(得分:1)
在" SET"
之后添加一个空格String sql = "Update Products SET "
+ "Description = ?, "
+ "Price = ? "
+ "Where Code = ?";
并最终在"值"
之前的空格String sql = "Insert into PRODUCTS(CODE, DESCRIPTION, PRICE)"
+ " Values(?, ?, ?)";
答案 1 :(得分:0)
您的查询中存在空格问题,同时在设置值时,顺序应为Descripcion,Price和Code。像这样:
private void editButtonActionPerformed(java.awt.event.ActionEvent evt)
{
String sql = "Update Products SET Description = ?, Price = ? "
+ "where Code = ?";
try
{
pstmt.setString(1, "DESCRIPTION");
pstmt.setDouble(2, Double.parseDouble("PRICE"));
pstmt.setString(3, "CODE");
int rowUpdated = pstmt.executeUpdate();
if (rowUpdated == 1)
{
JOptionPane.showMessageDialog(null,
"record updated successfully");
}
// Clean-up environment
rs.close();
pstmt.close();
con.close();
} catch (SQLException e)
{
JOptionPane.showMessageDialog(Product.this, e.getMessage());
}
}