[英]Netbeans java application - executing query on MySql database
在我正在从事的项目中,我需要执行Searching 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;
在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行中,我插入了通配符(%),但这不起作用。 我该如何解决?
您的通配符放错了位置。 它应该是:
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+"%%\"");
特别注意报价
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.