【发布时间】:2020-01-14 10:20:02
【问题描述】:
我已经制作了一个 JFrame 表单和一个数据库,该数据库将来自 jTable 的数据馈送到 JFrame 表单的其中一个面板中。当用户在用作搜索栏的jTextField 中输入内容时,SEARCH 查询会显示整个表,而不仅仅是特定记录。我不知道如何在代码中添加 WHERE 条件。
目前,用户可以在搜索栏中输入任何内容,按下搜索按钮并查看数据库中的所有信息。我尝试使用该语句:
myDataObj = myStatObj.executeQuery ("Select* from Gabrielle.PlantData where PName = 'search'");
但所有这些都只是一张空白表格。
Connection myConObj = null;
Statement myStatObj = null;
ResultSet myDataObj = null;
public WikiPlantGUI()
{
initComponents();
selectionAll();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
public void selectionAll()
{
try
{
myConObj= DriverManager.getConnection ("jdbc:derby://localhost:1527/InfoDB", "Gabrielle", "plants");
myStatObj = myConObj.createStatement();
myDataObj = myStatObj.executeQuery ("Select* from Gabrielle.PlantData where PName = 'search'");
guiTable.setModel(DbUtils.resultSetToTableModel(myDataObj) );
}
//Then there is some code that creates the JFrame form
private void mainSearchbtnActionPerformed(java.awt.event.ActionEvent evt) {
boolean valid = true;
String search = mainSearch.getText();
if (search.length() ==0)
{
valid = false;
}
else
{
basePanel.removeAll();
basePanel.add(dispPanel);
basePanel.repaint();
basePanel.revalidate();
}
我使用设计视图创建了数据库,所以我不知道如何显示代码。数据库有以下字段:
-
ID(主键), -
PName(搜索涉及的字段), -
PLevel, -
PArea, -
PType, -
PWater, -
PSun。
他们都是VARCHAR,除了PSun,它是INTEGER。
我现在要做的是获取用户在jTextField 中输入的数据(保存为字符串搜索),在数据库中搜索该数据,然后在表中仅显示单个记录用户输入的数据与表中名为PName 的特定字段匹配。
如果有什么太笼统的地方,我深表歉意,这是我第一次使用这个网站。请尽量使用简单的解释,因为我对编程也比较陌生。任何帮助表示赞赏。
【问题讨论】:
-
where PName = 'search'表示使用文字字符串值search。您需要使用带参数的准备好的语句。 -
首先在命令行应用程序中获取数据库访问权限。 (没有图形用户界面)。然后如果你不能解决它,发布一个与此相关的minimal reproducible example。