0

I have a SQL Server 2008 database and I want to select data by using a String variable... here is the selection code in java:

try {

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:DDS_DSN");
    Statement st = con.createStatement();
    ResultSet rs;

    rs = st.executeQuery("SELECT source_port FROM request_dns WHERE destination_port = 53");
    while ( rs.next() ) {
        String source_port = rs.getString("source_port");
        System.out.println(source_port);
    }
    con.close();
} catch (Exception e) {
    System.out.println(e);

}

I want to make it like this:

String x = "53";
try
{
.
.
rs = st.executeQuery("SELECT source_port FROM request_dns WHERE destination_port = x");
.
.
}

could you please tell me how to do that?... Thank you

Kind Regards

Gord Thompson
  • 116,920
  • 32
  • 215
  • 418

1 Answers1

0

You want a parameterized query, like this:

int x = 53;
PreparedStatement ps = con.prepareStatement(
        "SELECT source_port FROM request_dns " +
        "WHERE destination_port = ?");
ps.setInt(1, x);
ResultSet rs = ps.executeQuery();
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418