选择在mysql中触发的查询错误

时间:2013-05-03 17:24:59

标签: java mysql swing

我收到此错误 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:'where子句'中的未知列'NIRAV',当我尝试执行以下代码时。

package all_forms;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;

public class Select_operation {

private Connection con=null;
private PreparedStatement pstmt=null;
private ResultSet rs=null;
String query;
public Select_operation(Connection conn)
{
    con=conn;
}
public ResultSet select(String search)
{
    query="select * from student where id="+search+" or name like'"+search+"%'";
    try
    {
        pstmt=con.prepareStatement(query);
        rs=pstmt.executeQuery();
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null, ""+e, "Error",JOptionPane.ERROR_MESSAGE);
    }
    return rs;
}

}

1 个答案:

答案 0 :(得分:3)

ID的值应该用字符串换行,因为你提供的是非数字值。

query="select * from student where id='"+search+"' or name like '"+search+"%'";
                                      ^ HERE     ^

您应该考虑使用PreparedStatement来避免SQL Injection

// con is your active connection

String sqlStatement = "SELECT * FROM student WHERE id = ? OR name LIKE ?";
PreparedStatement prest = con.prepareStatement(sqlStatement);
prest.setString(1, search);
prest.setString(2, search + "%");
ResultSet _set = prest.executeQuery();

你还应该在课堂上添加这一行

import java.sql.*;

PreparedStatements避免使用sql注入代码。

<强> more on this link