在我正在进行的项目中,我需要执行搜索SQL查询,即Java中的通配符。我能够执行简单的查询,比如
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;在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 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行中,我插入了通配符(%),但这是行不通的。我怎么才能解决这个问题?
发布于 2015-09-20 17:03:56
你的通配符角色放错位置了。它应该是:
ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid+"%");在这种情况下,% char将被视为通配符。
如果要搜索% char本身,则必须按照mysql转义规则转义它:
ResultSet rs = stm.executeQuery("select*from employees where empid like \""+empid+"%%\"");特别注意引号
https://stackoverflow.com/questions/32681942
复制相似问题