Using an SQL Statement to Modify Data

 

DownloadDownload JDBC Driver

To modify the data that is contained in a SQL Server database by using an 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 AdventureWorks sample database is passed in to the function, an 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 {
      String SQL = "INSERT INTO TestTable (Col2, Col3) VALUES ('a', 10)";
      Statement stmt = con.createStatement();
      int count = stmt.executeUpdate(SQL);
      System.out.println("ROWS AFFECTED: " + count);
      stmt.close();
   }
   catch (Exception e) {
      e.printStackTrace();
   }
}

System_CAPS_ICON_note.jpg Note


If you must use an 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.

Using Statements with SQL

Community Additions

ADD
Show: