Java Reference
In-Depth Information
If this same database were remote, then the above line would look something
like this:
Connection connection =
"", "");
However, the API-specifi ed syntax is only a recommendation and database
vendors are free to ignore this if they wish. Consequently, some drivers may specify
sub-protocols and data sources with syntax that is different from that shown above.
It is up to the DriverManager to query each loaded driver in turn to determine
whether the driver recognises the type of database that is being addressed.
2. Create a Statement Object and Store Its Reference
A Statement object is created by calling the createStatement method of our
Connection object (whose reference was saved in variable link in the previous step).
The address of the object returned by this call to createStatement is saved in a
Statement reference. In the line below, this reference is simply called statement .
Statement statement = connection.createStatement();
3. Run a Query or Update and Accept the Result(s)
DML (Data Manipulation Language) statements in SQL may be divided into two
categories: those that retrieve data from a database (i.e., SELECT statements) and
those that change the contents of the database in some way (viz., INSERT, DELETE
and UPDATE statements). Class Statement has methods executeQuery and execute-
Update that are used to execute these two categories respectively. The former
method returns a ResultSet object, while the latter returns an integer that indicates
the number of database rows that have been affected by the updating operation.
(We shall postpone consideration of method executeUpdate until the next section.)
It is common practice to store the SQL query in a String variable and then invoke
executeQuery with this string as an argument, in order to avoid a rather cumbersome
invocation line. This practice has been followed in the examples below.
(i) String selectAll = "SELECT * FROM Accounts";
ResultSet results =
(ii) String selectFields =
"SELECT acctNum, balance FROM Accounts";
ResultSet results =
(iii) String selectRange = "SELECT * FROM Accounts"
+ " WHERE balance >= 0"
+ " AND balance <= 1000"
Search WWH ::

Custom Search