我有这个当前的GUI,在这里我应该能够从数据库条目中检索数据,并将现有数据放入文本字段/文本区域中,在其中我可以编辑数据,然后保存新的更改。我通过使用java类共享变量的设置器和获取器,从在此GUI之前加载的GUI中获得要搜索的名称。不幸的是,现在它不会向文本字段/文本区域加载数据,而是像我添加一个全新的条目一样。但我只希望它完全替换它已访问的条目。
package Cookbook;
import DatabaseEntry.Applicant;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class modifyingRecipe extends javax.swing.JFrame {
SearchRecipe sr;
/**
* Creates new form modifyingRecipe
*/
public modifyingRecipe() {
initComponents();
sr = new SearchRecipe();
presetPage();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here
try {
String url = "jdbc:derby://localhost:1527/Cookbook";
Connection conn = DriverManager.getConnection(url);
String query = "INSERT into RECIPES(NAME, SUBCATEGORY, CATEGORY, INGREDIENTS,
INSTRUCTIONS, MODIFICATIONS) values(?,?,?,?,?,?)";
PreparedStatement pst = conn.prepareStatement(query);
pst.setString(1, txtName.getText());
pst.setString(2, txtSubcategory.getText());
pst.setString(3, cmbCategory.getSelectedItem().toString());
pst.setString(4, txtIngredients.getText());
pst.setString(5, txtInstructions.getText());
pst.setString(6, txtMod.getText());
pst.executeUpdate();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
this.dispose();
CookbookApp c = new CookbookApp();
c.setVisible(true);
JOptionPane.showMessageDialog(null, "Recipe successfully modified!");
}
public ArrayList<Cookbook> getList() {
ArrayList<Cookbook> recipeList = new ArrayList();
try {
String url = "jdbc:derby://localhost:1527/Cookbook;databaseName=Cookbook";
Connection conn = DriverManager.getConnection(url);
String query = "SELECT * FROM RECIPES";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
Cookbook recipe;
while (rs.next()) {
recipe = new Cookbook(rs.getString("NAME"), rs.getString("SUBCATEGORY"),
rs.getString("CATEGORY"), rs.getString("INGREDIENTS"), rs.getString("INSTRUCTIONS"),rs.getString("MODIFICATIONS"));
recipeList.add(recipe);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
return recipeList;
}
public void presetPage(){
String name = sr.getSearch();
ArrayList<Cookbook> recipeList = getList();
for (int i = 0; i < recipeList.size(); i++) {
if (recipeList.get(i).getName().equals(name)){
txtName.setText(recipeList.get(i).getName());
cmbCategory.setSelectedItem(recipeList.get(i).getCategory());
txtSubcategory.setText(recipeList.get(i).getSubcategory());
txtIngredients.setText(recipeList.get(i).getIngredients());
txtInstructions.setText(recipeList.get(i).getInstructions());
txtMod.setText(recipeList.get(i).getModifications());
}
}
}