在我的程序中,我可以使用jTextfield" txtsearch"使用此代码在jTable中搜索数据。在我的计划中。
请看一下我的实际节目。这是一张图片:
这是我在jTextField" txtsearch"中的代码。在这段代码中
我只能通过Name
搜索jTable。我想使用jComboBox进行搜索。
String a=txtsearch.getText();
conn=MyConnection.ConnectDB();
String sql="Select* from StdRecord WHERE Name LIKE'"+a+"%'";
try{
pst=conn.prepareStatement(sql);
rst=pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rst));
}catch(Exception e){}
另外,根据我上传的图片,我的问题是:如何使用组合框按Name
,MiddleName
和Surname
搜索学生?
例如,我在组合框中选择MiddleName
,然后当我输入jTextField" txtsearch"我只能在表格的MiddleName
部分进行搜索。
答案 0 :(得分:1)
这是我在jTextField“txtsearch”中的代码。在这段代码中,我只能通过Name搜索jTable。我想使用jComboBox进行搜索。
您当前的SQL是否为您要搜索的数据使用了一个变量,那么为什么不能为要搜索的列使用变量呢?
String a=txtsearch.getText();
String column = comboBox.getSelectedItem().toString();
String sql="Select* from StdRecord WHERE " + column + "LIKE'"+a+"%'";
此外,为了使SQL更容易编码和维护,您应该使用PreparedStatement
:
String sql = "Select* from StdRecord WHERE " + column + "LIKE ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, a + "%" );
stmt.executeQuery();