在我正在工作的项目中,我需要执行搜索SQL查询,即Java Netbeans中的通配符。我能够执行简单的查询,如
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);
}
这完全可以正常工作。但现在我想使用这个MySql查询
Mysql>select * from employes where empid like "123%";
而不是
Mysql>select * from employes where empid =123;
我已经试过了
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);
}
您可以看到,在第8行中,我插入了通配符(%),但这不起作用。我怎么解决这个问题?
您的通配符放错了位置。应该是:
ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid+"%");
在这种情况下,%字符将被视为通配符。
如果你想搜索%字符本身,你必须按照mysql的转义规则转义它:
ResultSet rs = stm.executeQuery("select*from employees where empid like ""+empid+"%%"");
要特别注意引号