No such column error jdbc

jdbcsqlite

Suppose I have a table:

SERVICE={SID,NAME,PORT}

and with the help of a Java program, I want to select the SID of the known port with the help of a SQL query:

Select SID from SERVICE where PORT=port

But when I write the code snippet:

String sql="Select SID from SERVICE where PORT=port;";

where port is an integer variable but on execution I get the following error:

No such column port".How to get rid of this error?

Best Answer

It is generally a terrible idea to construct SQL queries the way you currently do, as it opens the door to all sorts of SQL injection attacks. To do this properly, you'll have to use Prepared Statements instead. This will also resolve all sorts of escaping issues that you're evidently having at the moment.

String[] port = new String[] {"3306"};
    PreparedStatement statement = connection.prepareStatement("String sql="Select SID from SERVICE where PORT= ?");

    for (String name: names) {
        statement.setString(1, port);    
        ResultSet resultSet = statement.executeQuery();
        ...
        ...
        statement.clearParameters();
    }