user2202010
user2202010

Reputation:

select query error fired in mysql

i am getting this error com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'NIRAV' in 'where clause' when i am trying to execute following code.

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

}

Upvotes: 1

Views: 104

Answers (1)

John Woo
John Woo

Reputation: 263853

the value of the ID should be wrap with a string because you are supplying a non numeric value of it.

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

you should consider using PreparedStatement to avoid 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();

you should also add this line on top of the class

import java.sql.*;

PreparedStatements avoid your code from sql injection.

more on this link

Upvotes: 3

Related Questions