我想在JFrame表单中使用textfield中的字符串输入作为我在java中的sql查询的一部分。 例如,如果我在textfield中输入名称,我希望sql查询使用该名称并提供相关数据而不是整个表的数据。比如“select * from * table_name * where name = * textfield_input *;” 以下是我用来获取整个表格数据的代码。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)p1.getModel();
try{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ritick","root", "iit2012054");
Statement st = con.createStatement();
String query = "select * from student;";
ResultSet rs = st.executeQuery(query);
while(rs.next()){
String d1 = rs.getString("roll_no");
String d2 = rs.getString("name");
String d3 = rs.getString("dept");
String d4 = rs.getString("cgpa");
model.addRow(new Object[]{d1,d2,d3,d4});
}
rs.close();
st.close();
con.close();
}
catch (Exception e){
JOptionPane.showMessageDialog(this, "error in connectivity !");
}
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)p2.getModel();
try{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ritick","root", "iit2012054");
Statement st = con.createStatement();
String query = "show databases;";
ResultSet rs = st.executeQuery(query);
while(rs.next()){
String d1 = rs.getString("database");
model.addRow(new Object[]{d1});
}
rs.close();
st.close();
con.close();
}
catch (Exception e){
JOptionPane.showMessageDialog(this, "error in connectivity !");
}
}
答案 0 :(得分:0)
这可能有助于尝试使用PreparedStatement 查询是“select * from student where name =?” 从语句setString(1,String)