简体   繁体   中英

Netbeans java application - executing query on MySql database

In the project I'm working on I need to execute Searching SQL query ie the wildcard characters in Java Netbeans. I'm able to execute simple queries like

    String driver = "jdbc:mysql://localhost/techo";
    String un = "root";
    String pw = "root";

    String empid = id.getText();

    try{

        Connection con = DriverManager.getConnection(driver,un,pw);
        Statement stm = con.createStatement();
        ResultSet rs = stm.executeQuery("select*from employees where empid ="+empid+"");

        while(rs.next())
        {
            String name = rs.getString("name");
            String salary = rs.getString("salary");
            name1.setText(name);
            salary1.setText(salary);
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null,e);
    }

This works completely fine. But now I want to use this MySql query

Mysql>select * from employes where empid like "123%";

instead of this

Mysql>select * from employes where empid =123;

in java Netbeans.

I've tried to do this

    String driver = "jdbc:mysql://localhost/techo";
    String un = "root";
    String pw = "root";

    String empid = id.getText();

    try{

        Connection con = DriverManager.getConnection(driver,un,pw);
        Statement stm = con.createStatement();
        ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid%+"");

        while(rs.next())
        {
            String id = rs.getString("EmpId");
            String name = rs.getString("name");
            String salary = rs.getString("salary");
            area.setText(id +"    "+name+"    "+salary+"    "+ "\n");
        }
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null,e);
    }

As you can see that in the 8th line I've inserted the wildcard character(%) but this ain't working. How can I solve this?

Your wildcard character is misplaced. It should be:

        ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid+"%");

In this case the % char will be treated as a wildcard.

If you want to search the % char itself, you have to escape it following the mysql escape rules:

        ResultSet rs = stm.executeQuery("select*from employees where empid like \""+empid+"%%\"");

Pay special attention to the quotes

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