Bewerken

Share via


Using a SQL statement to modify data

Download JDBC driver

To modify the data that is contained in a SQL Server database by using a SQL statement, you can use the executeUpdate method of the SQLServerStatement class. The executeUpdate method will pass the SQL statement to the database for processing, and then return a value that indicates the number of rows that were affected.

To do this, you must first create a SQLServerStatement object by using the createStatement method of the SQLServerConnection class.

In the following example, an open connection to the AdventureWorks2022 sample database is passed in to the function, a SQL statement is constructed that adds new data to the table, and then the statement is run and the return value is displayed.

public static void executeUpdateStatement(Connection con) {
    try(Statement stmt = con.createStatement();) {
        String SQL = "INSERT INTO TestTable (Col2, Col3) VALUES ('a', 10)";
        int count = stmt.executeUpdate(SQL);
        System.out.println("ROWS AFFECTED: " + count);
    }
    // Handle any errors that may have occurred.
    catch (SQLException e) {
        e.printStackTrace();
    }
}

Note

If you must use a SQL statement that contains parameters to modify the data in a SQL Server database, you should use the executeUpdate method of the SQLServerPreparedStatement class.

If the column that you are trying to insert data into contains special characters such as spaces, you must provide the values to be inserted, even if they are default values. If you do not, the insert operation will fail.

If you want the JDBC driver to return all update counts, including update counts returned by any triggers that may have fired, set the lastUpdateCount connection string property to "false". For more information about the lastUpdateCount property, see Setting the connection properties.

See also

Using statements with SQL