Using a SQL statement to modify database objects
To modify SQL Server database objects 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 of 0 because no rows were affected.
To do this, you must first create a SQLServerStatement object by using the createStatement method of the SQLServerConnection class.
Note
SQL statements that modify objects within a database are called Data Definition Language (DDL) statements. These include statements such as CREATE TABLE
, DROP TABLE
, CREATE INDEX
, and DROP INDEX
. For more information about the types of DDL statements that are supported by SQL Server, see SQL Server Books Online.
In the following example, an open connection to the AdventureWorks2022 sample database is passed in to the function, a SQL statement is constructed that will create the simple TestTable in the database, 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 = "CREATE TABLE TestTable (Col1 int IDENTITY, Col2 varchar(50), Col3 int)";
int count = stmt.executeUpdate(SQL);
System.out.println("ROWS AFFECTED: " + count);
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
}