简体   繁体   中英

java database connectivity: jdbc

i want to use the string input in textfield in JFrame form as a part of my sql query in java. For example if i input a name in textfield, i want the sql query to use that name and give the relevant data and not the data of entire table. Like "select * from *table_name* where name = *textfield_input* ;" following is the code that i'm using to get the data of the entire table.

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

This might help Try to use the PreparedStatement so that Query is "select * from student where name = ?" From the statement setString(1, String)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM