0

In the project I'm working on I need to execute Searching SQL query i.e 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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.