Tabnine Logo
Connection.prepareStatement
PreparedStatement.executeUpdate
try
Code IndexAdd Tabnine to your IDE (free)

How to use
prepareStatement
method
in
java.sql.Connection

Updating database using SQL prepared statement

Refine searchRefine arrow

  • PreparedStatement.setString
  • PreparedStatement.close
  • PreparedStatement.setInt
  • Connection.close
  • ResultSet.next
  • PreparedStatement.executeQuery
  • PreparedStatement.setLong
  • AbstractJdbcInsert.getGeneratedKeyNames
  • Connection
  • PreparedStatement
  • StdJDBCDelegate
  • AbstractJdbcInsert
origin: iluwatar/java-design-patterns

 /**
  * {@inheritDoc}
  */
 @Override
 public boolean delete(Customer customer) throws Exception {
  try (Connection connection = getConnection();
    PreparedStatement statement = 
      connection.prepareStatement("DELETE FROM CUSTOMERS WHERE ID = ?")) {
   statement.setInt(1, customer.getId());
   return statement.executeUpdate() > 0;
  } catch (SQLException ex) {
   throw new CustomException(ex.getMessage(), ex);
  }
 }
}
origin: iluwatar/java-design-patterns

/**
 * {@inheritDoc}
 */
@Override
public boolean update(Customer customer) throws Exception {
 try (Connection connection = getConnection();
   PreparedStatement statement = 
     connection.prepareStatement("UPDATE CUSTOMERS SET FNAME = ?, LNAME = ? WHERE ID = ?")) {
  statement.setString(1, customer.getFirstName());
  statement.setString(2, customer.getLastName());
  statement.setInt(3, customer.getId());
  return statement.executeUpdate() > 0;
 } catch (SQLException ex) {
  throw new CustomException(ex.getMessage(), ex);
 }
}
origin: stackoverflow.com

 public void create(Entity entity) throws SQLException {
  Connection connection = null;
  PreparedStatement statement = null;

  try { 
    connection = dataSource.getConnection();
    statement = connection.prepareStatement(SQL_CREATE);
    statement.setSomeObject(1, entity.getSomeProperty());
    // ...
    statement.executeUpdate();
  } finally {
    if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
    if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
  }
}
origin: quartz-scheduler/quartz

public int deleteFiredTriggers(Connection conn, String theInstanceId)
  throws SQLException {
  PreparedStatement ps = null;
  try {
    ps = conn.prepareStatement(rtp(DELETE_INSTANCES_FIRED_TRIGGERS));
    ps.setString(1, theInstanceId);
    return ps.executeUpdate();
  } finally {
    closeStatement(ps);
  }
}
origin: spotbugs/spotbugs

void f2() throws SQLException {
  PreparedStatement insertFieldAudit = null;
  try {
    insertFieldAudit = getConnection().prepareStatement(INSERT_FIELD_AUDIT);
    insertFieldAudit.executeUpdate();
    insertFieldAudit = getConnection().prepareStatement(INSERT_FIELD_AUDIT);
    insertFieldAudit.executeUpdate();
  } finally {
    insertFieldAudit.close();
  }
}
origin: Kaaz/DiscordBot

  public int insert(String sql, Object... params) throws SQLException {
    try (PreparedStatement query = getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
      resolveParameters(query, params);
      query.executeUpdate();
      ResultSet rs = query.getGeneratedKeys();

      if (rs.next()) {
        return rs.getInt(1);
      }
    }
    return -1;
  }
}
origin: stackoverflow.com

 public insertUser(String name, String email) {
  Connection conn = null;
  PreparedStatement stmt = null;
  try {
   conn = setupTheDatabaseConnectionSomehow();
   stmt = conn.prepareStatement("INSERT INTO person (name, email) values (?, ?)");
   stmt.setString(1, name);
   stmt.setString(2, email);
   stmt.executeUpdate();
  }
  finally {
   try {
     if (stmt != null) { stmt.close(); }
   }
   catch (Exception e) {
     // log this error
   }
   try {
     if (conn != null) { conn.close(); }
   }
   catch (Exception e) {
     // log this error
   }
  }
}
origin: quartz-scheduler/quartz

public int deleteSchedulerState(Connection conn, String theInstanceId)
  throws SQLException {
  PreparedStatement ps = null;
  try {
    ps = conn.prepareStatement(rtp(DELETE_SCHEDULER_STATE));
    ps.setString(1, theInstanceId);
    return ps.executeUpdate();
  } finally {
    closeStatement(ps);
  }
}
origin: spotbugs/spotbugs

void f() throws SQLException {
  PreparedStatement insertFieldAudit = null;
  try {
    for (int i = 1; i <= 10; i++) {
      insertFieldAudit = getConnection().prepareStatement(INSERT_FIELD_AUDIT);
      insertFieldAudit.executeUpdate();
    }
  } finally {
    insertFieldAudit.close();
  }
}
origin: stackoverflow.com

 public void create(Entity entity) throws SQLException {
  Connection connection = null;
  PreparedStatement statement = null;

  try { 
    connection = database.getConnection();
    statement = connection.prepareStatement(SQL_CREATE);
    statement.setSomeObject(1, entity.getSomeProperty());
    // ...
    statement.executeUpdate();
  } finally {
    if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
    if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
  }
}
origin: apache/activemq

@Override
public void doDeleteOldMessages(TransactionContext c) throws SQLException, IOException {
  PreparedStatement s = null;
  try {
    LOG.debug("Executing SQL: " + this.statements.getDeleteOldMessagesStatementWithPriority());
    s = c.getExclusiveConnection().prepareStatement(this.statements.getDeleteOldMessagesStatementWithPriority());
    int priority = priorityIterator++%10;
    s.setInt(1, priority);
    s.setInt(2, priority);
    int i = s.executeUpdate();
    LOG.debug("Deleted " + i + " old message(s) at priority: " + priority);
  } finally {
    close(s);
  }
}
origin: spring-projects/spring-framework

logger.debug("The following parameters are used for call " + getInsertString() + " with: " + values);
getJdbcTemplate().update(
    con -> {
      PreparedStatement ps = prepareStatementForGeneratedKeys(con);
      setParameterValues(ps, values, getInsertTypes());
      return ps;
      "The getGeneratedKeys feature is not supported by this database");
if (getGeneratedKeyNames().length < 1) {
  throw new InvalidDataAccessApiUsageException("Generated Key Name(s) not specified. " +
      "Using the generated keys features requires specifying the name(s) of the generated column(s)");
if (getGeneratedKeyNames().length > 1) {
  throw new InvalidDataAccessApiUsageException(
      "Current database only supports retrieving the key for a single column. There are " +
      getGeneratedKeyNames().length  + " columns specified: " + Arrays.asList(getGeneratedKeyNames()));
    try {
      ps = con.prepareStatement(getInsertString());
      setParameterValues(ps, values, getInsertTypes());
      ps.executeUpdate();
origin: gocd/gocd

static void perform(Connection cxn, long id, String selections, boolean isBlacklist) throws SQLException {
  try (PreparedStatement ps = cxn.prepareStatement("UPDATE pipelineselections SET selections = NULL, version = ?, filters = ? WHERE id = ?")) {
    ps.setInt(1, SCHEMA);
    ps.setString(2, asJson(selections, isBlacklist));
    ps.setLong(3, id);
    ps.executeUpdate();
  }
}
origin: quartz-scheduler/quartz

public int deleteSchedulerState(Connection conn, String theInstanceId)
  throws SQLException {
  PreparedStatement ps = null;
  try {
    ps = conn.prepareStatement(rtp(DELETE_SCHEDULER_STATE));
    ps.setString(1, theInstanceId);
    return ps.executeUpdate();
  } finally {
    closeStatement(ps);
  }
}
origin: camunda/camunda-bpm-platform

public int update(String sql, Object... args) throws SQLException {
 PreparedStatement ps = connection.prepareStatement(sql);
 try {
  setParameters(ps, args);
  return ps.executeUpdate();
 } finally {
  try {
   ps.close();
  } catch (SQLException e) {
   //ignore
  }
 }
}
origin: requery/requery

TransactionListener transactionListener = new CompositeTransactionListener(
    configuration.getTransactionListenerFactories());
try {
  Connection connection = configuration.getConnection();
  StatementListener listener = configuration.getStatementListener();
  if (query.insertType() == InsertType.SELECT) {
    statement = connection.prepareStatement(sql, Statement.NO_GENERATED_KEYS);
  } else {
    statement = prepare(sql, connection);
  transactionListener.beforeCommit(types);
  count = statement.executeUpdate();
    connection.close();
    MutableTuple tuple = new MutableTuple(1);
    tuple.set(0, NamedExpression.ofInteger("count"), count);
    return new CollectionResult<Tuple>(tuple);
  } else {
    ResultSet results = statement.getGeneratedKeys();
    return new GeneratedKeyResult(configuration, selection, connection, results, count);
origin: apache/sqoop

private void insertRowIntoTestTable() throws SQLException {
 try (Connection conn = connectionFactory.createConnection(); PreparedStatement stmnt = conn.prepareStatement(INSERT_SQL)) {
  stmnt.setInt(1, TEST_VALUE);
  stmnt.executeUpdate();
 }
}
origin: gocd/gocd

static void perform(Connection cxn, long id, String filters) throws SQLException {
  try (PreparedStatement ps = cxn.prepareStatement("UPDATE pipelineselections SET version = ?, filters = ? WHERE id = ?")) {
    ps.setInt(1, SCHEMA);
    ps.setString(2, addStateIfNull(filters));
    ps.setLong(3, id);
    ps.executeUpdate();
  }
}
origin: quartz-scheduler/quartz

public int deletePausedTriggerGroup(Connection conn, GroupMatcher<TriggerKey> matcher)
  throws SQLException {
  PreparedStatement ps = null;
  try {
    ps = conn.prepareStatement(rtp(DELETE_PAUSED_TRIGGER_GROUP));
    ps.setString(1, toSqlLikeClause(matcher));
    int rows = ps.executeUpdate();
    return rows;
  } finally {
    closeStatement(ps);
  }
}
origin: spotbugs/spotbugs

@ExpectWarning("ODR_OPEN_DATABASE_RESOURCE")
public static void test0(String url) throws Exception {
  Connection conn;
  PreparedStatement pstm = null;
  try {
    conn = DriverManager.getConnection(url);
    pstm = conn.prepareStatement("123");
    pstm.executeUpdate();
  } finally {
    if (pstm != null)
      pstm.close();
  }
}
java.sqlConnectionprepareStatement

Javadoc

Returns a new instance of PreparedStatement that may be used any number of times to execute parameterized requests on the database server.

Subject to JDBC driver support, this operation will attempt to send the precompiled version of the statement to the database. If the driver does not support precompiled statements, the statement will not reach the database server until it is executed. This distinction determines the moment when SQLExceptions get raised.

By default, ResultSets from the returned object will be ResultSet#TYPE_FORWARD_ONLY type with a ResultSet#CONCUR_READ_ONLY mode of concurrency.

Popular methods of Connection

  • close
    Causes the instant release of all database and driver connection resources associated with this obje
  • createStatement
    Returns a new instance of Statement whose associated ResultSets will have the characteristics specif
  • getMetaData
    Gets the metadata about the database referenced by this connection. The returned DatabaseMetaData de
  • commit
    Commits all of the changes made since the last commit or rollback of the associated transaction. All
  • setAutoCommit
    Sets this connection's auto-commit mode on or off. Putting a Connection into auto-commit mode means
  • rollback
    Undoes all changes made after the supplied Savepoint object was set. This method should only be used
  • isClosed
    Returns a boolean indicating whether or not this connection is in the closed state. The closed state
  • getAutoCommit
    Returns a boolean indicating whether or not this connection is in the auto-commit operating mode.
  • setTransactionIsolation
    Sets the transaction isolation level for this Connection. If this method is called during a transact
  • prepareCall
    Returns a new instance of CallableStatement that may be used for making stored procedure calls to th
  • getCatalog
    Gets this Connection object's current catalog name.
  • getTransactionIsolation
    Returns the transaction isolation level for this connection.
  • getCatalog,
  • getTransactionIsolation,
  • setReadOnly,
  • isValid,
  • clearWarnings,
  • getWarnings,
  • setSavepoint,
  • isReadOnly,
  • setCatalog

Popular in Java

  • Reactive rest calls using spring rest template
  • setScale (BigDecimal)
  • getSharedPreferences (Context)
  • findViewById (Activity)
  • BorderLayout (java.awt)
    A border layout lays out a container, arranging and resizing its components to fit in five regions:
  • Scanner (java.util)
    A parser that parses a text string of primitive types and strings with the help of regular expressio
  • Callable (java.util.concurrent)
    A task that returns a result and may throw an exception. Implementors define a single method with no
  • StringUtils (org.apache.commons.lang)
    Operations on java.lang.String that arenull safe. * IsEmpty/IsBlank - checks if a String contains
  • Location (org.springframework.beans.factory.parsing)
    Class that models an arbitrary location in a Resource.Typically used to track the location of proble
  • Option (scala)
  • Top plugins for WebStorm
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimAtomGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyStudentsTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now