Creating and Executing JDBC Statements
|
|
We need to create a Statement object to send request and retrieve result from a database. The Connection object provide the createStatement ( ) method to create a Statement object. |
|
We can use the following code to create a Statement object: |
|
Connection con =DriverManager.getConnection |
|
(“jdbc:odbc:MyDSN”, “NewUser”, “NewPassword”); |
|
Statement stmt= con.createStatement ( ); |
|
We can use the static SQL statement to send request to a database. |
|
Here we can use the send the SQL statement to a database using the Statement object. |
|
The Statement interface contain the following methods to send static SQL statement to the database:—– |
|
1. ResultSet executeQuery(String str):– It execute an SQL statement and returns a single object of the type, ResultSet. |
|
The syntax to use the executeQuery ( ) method is : |
|
Statement stmt = con.createStatement ( ); |
|
ResultSet rs = stmt.executeQuery(<SQL statement>); |
|
2. int executeUpdate (String str):– It execute the SQL statements and returns the number of data rows that are affected after processing the SQL statement. The executeUpdate ( ) can be used when we need to INSERT, DELETE, and UPDATE the data. |
|
Statement stmt = con.createStatement ( ); |
|
ResultSet rs = stmt.execute(<SQL statement>); |
|
3. Boolean execute(String str): This method execute an SQL statement and return a Boolean |
|
Statement stmt = con.createStatement ( ); |
|
stmt.execute(<SQL statement>); |