[英]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. 在我正在从事的项目中,我需要执行Searching SQL查询,即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查询
Mysql>select * from employes where empid like "123%";
instead of this 代替这个
Mysql>select * from employes where empid =123;
in java Netbeans. 在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. 如您所见,在第8行中,我插入了通配符(%),但这不起作用。 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. 在这种情况下,%char将被视为通配符。
If you want to search the % char itself, you have to escape it following the mysql escape rules: 如果要搜索%char本身,则必须按照mysql转义规则对其进行转义:
ResultSet rs = stm.executeQuery("select*from employees where empid like \""+empid+"%%\"");
Pay special attention to the quotes 特别注意报价
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.