1

当我尝试执行以下代码时,我收到此错误com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'NIRAV' in 'where Clause' 。

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;
}

}

4

1 回答 1

3

的值ID应该用字符串包装,因为您提供的是它的非数字值。

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

您应该考虑使用PreparedStatementto 避免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 注入。

更多关于这个链接

于 2013-05-03T17:27:50.280 回答