Parameterized SQL statement

From Rosetta Code
Revision as of 19:43, 7 October 2009 by rosettacode>Mwn3d (Created task with Java. I hope it's OK.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Parameterized SQL statement
You are encouraged to solve this task according to the task description, using any language you may know.

Using a SQL update statement like this one

UPDATE players SET name = 'Smith, Steve', score = 42, active = true WHERE jerseyNum = 99

show how to make a parameterized SQL statement, set the parameters to the values given above, and execute the statement.

Java

<lang java>import java.sql.DriverManager; import java.sql.Connection; import java.sql.PreparedStatement;

public class DBDemo{

  private String protocol; //set this to some connection protocol like "jdbc:sqlserver://"
  private String dbName; //set this to the name of your database
  private String username;
  private String password;
  Connection conn = DriverManger.getConnection(protocol + dbName, username, password);
  PreparedStatement query;
  public int setUpAndExecPS(){
     query = conn.prepareStatement("UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?");
     query.setString(1, "Smith, Steve");//automatically sanitizes and adds quotes
     query.setInt(2, 42);
     query.setBoolean(3, true);
     query.setInt(4, 99);
     //there are similar methods for other SQL types in PerparedStatement
     return query.executeUpdate();//returns the number of rows changed
     //PreparedStatement.executeQuery() will return a java.sql.ResultSet,
     //execute() will simply return a boolean saying whether it succeeded or not
  }

}</lang>