Using an SQL statement to modify database objects
To modify SQL Server database objects 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 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, an 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();
}
}
See also
Feedback
https://aka.ms/ContentUserFeedback.
Kommer snart: I hele 2024 udfaser vi GitHub-problemer som feedbackmekanisme for indhold og erstatter det med et nyt feedbacksystem. Du kan få flere oplysninger under:Indsend og få vist feedback om