Example usage for java.sql Statement executeUpdate

List of usage examples for java.sql Statement executeUpdate

Introduction

In this page you can find the example usage for java.sql Statement executeUpdate.

Prototype

int executeUpdate(String sql, String columnNames[]) throws SQLException;

Source Link

Document

Executes the given SQL statement and signals the driver that the auto-generated keys indicated in the given array should be made available for retrieval.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);

    String insert = "INSERT INTO orders (username, order_date) VALUES ('foobar', '2007-12-13')";
    Statement stmt = conn.createStatement();

    stmt.executeUpdate(insert, Statement.RETURN_GENERATED_KEYS);

    ResultSet keys = stmt.getGeneratedKeys();
    int lastKey = 1;
    while (keys.next()) {
        lastKey = keys.getInt(1);/* w  w  w  .ja  va  2 s.com*/
    }
    System.out.println("Last Key: " + lastKey);
    conn.close();
}

From source file:hu.bme.mit.trainbenchmark.sql.SQLDatabaseDriver.java

@Override
public Long insertVertexWithEdge(final Long sourceVertex, final String sourceVertexType,
        final String targetVertexType, final String edgeType) throws IOException {
    long newVertexId = -1;
    try {/* w w  w. j ava2s . c om*/
        final Statement st = con.createStatement();
        st.executeUpdate(String.format("INSERT INTO `%s` VALUES ();", targetVertexType),
                Statement.RETURN_GENERATED_KEYS);

        try (ResultSet rs = st.getGeneratedKeys()) {
            if (rs.next()) {
                newVertexId = rs.getLong(1);

                String update;
                if (SENSOR_EDGE.equals(edgeType)) {
                    update = String.format("UPDATE `%s` SET `%s` = %d WHERE `%s` = %d;", TRACKELEMENT,
                            SENSOR_EDGE, newVertexId, ID, sourceVertex);
                } else {
                    update = String.format("INSERT INTO `%s` (`%s`, `%s`) VALUES (%d, %d);", edgeType,
                            EDGE_SOURCE_TYPES.get(edgeType), EDGE_TARGET_TYPES.get(edgeType), sourceVertex,
                            newVertexId);
                }
                st.executeUpdate(update);
            }
        }
    } catch (final SQLException e) {
        throw new IOException(e);
    }
    return newVertexId;
}