java数据库连接:jdbc

时间:2014-01-18 23:07:01

标签: java mysql jdbc

我想在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 !");
    }
}                                        

1 个答案:

答案 0 :(得分:0)

这可能有助于尝试使用PreparedStatement 查询是“select * from student where name =?” 从语句setString(1,String)