Skip to content

Commit

Permalink
Merge pull request #1945 from EnterpriseDB/content/jdbc_connector/42.…
Browse files Browse the repository at this point in the history
…2.12.3/Update

Updated the content for JDBC 42.2.12.3 and 42.2.19.1 version as per EC-1745
  • Loading branch information
nidhibhammar authored Oct 29, 2021
2 parents 288be6e + 4dc0b6d commit 2359d55
Show file tree
Hide file tree
Showing 7 changed files with 187 additions and 180 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: "Executing SQL Commands with executeUpdate()"
title: "Executing SQL Commands with executeUpdate() or through PrepareStatement Objects"

legacyRedirectsGenerated:
# This list is generated by a script. If you need add entries, use the `legacyRedirects` key.
Expand Down Expand Up @@ -33,55 +33,35 @@ public void updateEmployee(Connection con)
{
try
{
Console console = System.console();
Statement stmt = con.createStatement();
String empno = console.readLine("Employee Number :");
String ename = console.readLine("Employee Name :");
int rowcount = stmt.executeUpdate("INSERT INTO emp(empno, ename)
VALUES("+empno+",'"+ename+"')");
int rowcount = stmt.executeUpdate("INSERT INTO "
+ "emp(empno, ename) VALUES(6000,'Jones')");
System.out.println("");
System.out.println("Success - "+rowcount+" rows affected.");
}
catch(Exception err)
{
System.out.println("An error has occurred.");
System.out.println("See full details below.");
err.printStackTrace();
System.out.println("Success - "+rowcount+
" rows affected.");
} catch(Exception err) {
System.out.println("An error has occurred.");
System.out.println("See full details below.");
err.printStackTrace();
}
}
```

The `updateEmployee()` method expects a single argument from the caller, a `Connection` object that must be connected to an Advanced Server database:

```text
public void updateEmployee(Connection con)
```

Next, `updateEmployee()` prompts the user for an employee name and number:

```text
String empno = console.readLine("Employee Number :");
String ename = console.readLine("Employee Name :");
public void updateEmployee(Connection con);
```

`updateEmployee()` concatenates the values returned by `console.readline()` into an `INSERT` statement and pass the result to the `executeUpdate()` method.

```text
int rowcount = stmt.executeUpdate("INSERT INTO emp(empno, ename)
VALUES("+empno+",'"+ename+"')");
```

For example, if the user enters an employee number of `6000` and a name of `Jones`, the `INSERT` statement passed to `executeUpdate()` will look like this:
The `executeUpdate()` method returns the number of rows affected by the SQL statement (an `INSERT` typically affects one row, but an `UPDATE` or `DELETE` statement can affect more).

```text
INSERT INTO emp(empno, ename) VALUES(6000, 'Jones');
int rowcount = stmt.executeUpdate("INSERT INTO emp(empno, ename)"
+" VALUES(6000,'Jones')");
```

The `executeUpdate()` method returns the number of rows affected by the SQL statement (an `INSERT` typically affects one row, but an `UPDATE` or `DELETE` statement can affect more). If `executeUpdate()` returns without throwing an error, the call to `System.out.println` displays a message to the user that shows the number of rows affected.
If `executeUpdate()` returns without throwing an error, the call to `System.out.println` displays a message to the user that shows the number of rows affected.

```text
System.out.println("");
System.out.println("");
System.out.println("Success - "+rowcount+" rows affected.");
```

Expand All @@ -95,37 +75,96 @@ err.printStackTrace();
}
```

### executeUpdate() Syntax Examples
You can use `executeUpdate()` with any SQL command that does not return a result set. However, you probably want to use `PrepareStatements` when the queries can be parameterized.

## Using PreparedStatements to Send SQL Commands

You can use `executeUpdate()` with any SQL command that does not return a result set. Some simple syntax examples using `executeUpdate()` with SQL commands follow:
Many applications execute the same SQL statement over and over again, changing one or more of the data values in the statement between each iteration. If you use a `Statement` object to repeatedly execute a SQL statement, the server must parse, plan, and optimize the statement every time. JDBC offers another `Statement` derivative, the `PreparedStatement` to reduce the amount of work required in such a scenario.

To use the `UPDATE` command with `executeUpdate()` to update a row:
Listing 1.4 demonstrates invoking a `PreparedStatement` that accepts an employee ID and employee name and inserts that employee information in the `emp` table:

```text
stmt.executeUpdate("UPDATE emp SET ename='"+ename+"' WHERE empno="+empno);
public void AddEmployee(Connection con)
{
try {
Console c = System.console();
String command = "INSERT INTO emp(empno,ename) VALUES(?,?)";
PreparedStatement stmt = con.prepareStatement(command);
stmt.setObject(1,new Integer(c.readLine("ID:")));
stmt.setObject(2,c.readLine("Name:"));
stmt.execute();
System.out.println("The procedure successfully executed.");
} catch(Exception err) {
System.out.println("An error has occurred.");
System.out.println("See full details below.");
err.printStackTrace();
}
}
```
Instead of hard-coding data values in the SQL statement, you insert `placeholders` to represent the values that will change with each iteration. Listing 1.4 shows an `INSERT` statement that includes two placeholders (each represented by a question mark):

To use the `DELETE` command with `executeUpdate()` to remove a row from a table:
```text
String command = "INSERT INTO emp(empno,ename) VALUES(?,?)";
```
With the parameterized SQL statement in hand, the `AddEmployee()` method can ask the `Connection` object to prepare that statement and return a `PreparedStatement` object:

```text
PreparedStatement stmt = con.prepareStatement(command);
```

At this point, the `PreparedStatement` has parsed and planned the `INSERT` statement, but it does not know what values to add to the table. Before executing the `PreparedStatement`, you must supply a value for each placeholder by calling a `setter` method. `setObject()` expects two arguments:

- A parameter number; parameter number one corresponds to the first question mark, parameter number two corresponds to the second question mark, etc.

- The value to substitute for the placeholder.

The `AddEmployee()` method prompts the user for an employee ID and name and calls `setObject()` with the values supplied by the user:

```text
stmt.executeUpdate("DELETE FROM emp WHERE empno="+empno);
stmt.setObject(1,new Integer(c.readLine("ID:")));
stmt.setObject(2, c.readLine("Name:"));
```

To use the DROP TABLE command with executeUpdate() to delete a table from a database:
And then asks the PreparedStatement object to execute the statement:

```text
stmt.executeUpdate("DROP TABLE tablename");
stmt.execute();
```

To use the `CREATE TABLE` command with `executeUpdate()` to add a new table to a database:
If the SQL statement executes as expected, `AddEmployee()` displays a message that confirms the execution. If the server encounters an exception, the error handling code displays an error message.

Some simple syntax examples using `PreparedStatement` sending SQL commands follow:

To use the UPDATE command to update a row:

```text
stmt.executeUpdate("CREATE TABLE tablename (fieldname NUMBER(4,2),
fieldname2 VARCHAR2(30))");
String command = " UPDATE emp SET ename=? WHERE empno=?";
PreparedStatement stmt = con.prepareStatement(command);
stmt.setObject(1, c.readLine("Name:"));
stmt.setObject(2,new Integer(c.readLine("ID:")));
stmt.execute();
```

To use the `ALTER TABLE` command with `executeUpdate()` to change the attributes of a table:
To use the DROP TABLE command to delete a table from a database:

```text
stmt.executeUpdate("ALTER TABLE tablename ADD COLUMN colname BOOLEAN");
String command = "DROP TABLE tableName";
PreparedStatement stmt = con.prepareStatement(command);
stmt.execute();
```

To use the CREATE TABLE command to add a new table to a database:

```text
String command = ("CREATE TABLE tablename (fieldname NUMBER(4,2), fieldname2 VARCHAR2(30))";
PreparedStatement stmt = con.prepareStatement(command);
stmt.execute();
```

To use the ALTER TABLE command to change the attributes of a table:

```text
String command ="ALTER TABLE tablename ADD COLUMN colname BOOLEAN ";
PreparedStatement stmt = con.prepareStatement(command);
stmt.execute();
```
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ legacyRedirectsGenerated:

<div id="adding_a_graphical_interface_to_a_java_program" class="registered_link"></div>

With a little extra work, you can add a graphical user interface to a program - the next example (Listing 1.4) demonstrates how to write a Java application that creates a `JTable` (a spreadsheet-like graphical object) and copies the data returned by a query into that `JTable`.
With a little extra work, you can add a graphical user interface to a program - the next example (Listing 1.5) demonstrates how to write a Java application that creates a `JTable` (a spreadsheet-like graphical object) and copies the data returned by a query into that `JTable`.

!!! Note
The following sample application is a method, not a complete application. To call this method, provide an appropriate main() function and wrapper class.

Listing 1.4
Listing 1.5

```text
import java.sql.*;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Batched result sets cannot be used in all situations. Not adhering to the follow

## Modifying the Batch Size of a Statement Object

Limiting the batch size of a `ResultSet` object can speed the retrieval of data and reduce the resources needed by a client-side application. Listing 1.5 creates a `Statement` object with a batch size limited to five rows:
Limiting the batch size of a `ResultSet` object can speed the retrieval of data and reduce the resources needed by a client-side application. Listing 1.6 creates a `Statement` object with a batch size limited to five rows:

```text
// Make sure autocommit is off
Expand Down

This file was deleted.

Loading

0 comments on commit 2359d55

Please sign in to comment.