Ganesh - Javase7 - Programming - 1Z0-804 - Study - Guide - PDF: Upload
Ganesh - Javase7 - Programming - 1Z0-804 - Study - Guide - PDF: Upload
☆
Размер: 5.88 Mб
Вуз: Национальный Технический Университет
Харьковский Политехнический Институт Скачать
Предмет: [НЕСОРТИРОВАННОЕ]
Файл: Ganesh_JavaSE7_Programming_1z0-
804_study_guide.pdf
<< < 77 78 79 80 81 82 83 84 85
< Предыдущая 86 87 88 89 90 91 92 93 94 95 96 Следующая >
97 98 > >>
Similarly, ResultSet provides a set of methods to update values at the desired column in the selected
row. These methods also come in two variants: void updateXXX(int columnNumber, XXX x) and void
updateXXX(String columnName, XXX x), where the update methods are defined for various data types
represented as XXX.
import java.sql.*;
// Program to illustrate how to query a database
class DbQuery {
public static void main(String[] args) {
// Get connection, execute query, get the result set
// and print the entries from the result rest
try (Connection connection = DbConnector.connectToDb();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while (resultSet.next()) {
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo"));
}
}
290
Наши эксперты
}
готовы помочь!
The output of the program is
Here, you are using column names to read the associated values. You can use column numbers
instead to do the same job. Here is the modified code inside the while loop to use column numbers
instead:
while (resultSet.next()) {
System.out.println(resultSet.getInt(1)
+ "\t" + resultSet.getString(2)
+ "\t" + resultSet.getString(3)
+ "\t" + resultSet.getString(4)
+ "\t" + resultSet.getString(5));
}
This code produces exactly the same result as the last example. However, one important thing to
observe here is that column index starts from 1, not from 0.
The column index in the ResultSet object starts from 1, not from 0.
►
Содержание
291
►
java.sql.SQLException: Column Index out of range, 6 > 5.
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
[. . . this part of the stack trace elided . . .]
at DbQuery.main(DbQuery.java:18)
Hence, you should be careful and always provide the correct column indices.
In this example, you know the number of columns as well as the data types in columns. What if you
neither know the number of columns in each row nor the data types in the columns? You can use the
getMetaData() method and use the getColumnCount() method to get the column count. When you don’t
know the data type of a column entry, you can just use the getObject() method on the ResultSet object.
Here is the modified code that makes use of these methods:
// from resultSet metadata, find out how many columns are there and then read the column entries
int numOfColumns = resultSet.getMetaData().getColumnCount();
while (resultSet.next()) {
// remember that the column index starts from 1 not 0
for(int i = 1; i <= numOfColumns; i++) {
// since we do not know the data type of the column, we use getObject()
System.out.print(resultSet.getObject(i) + "\t");
}
System.out.println("");
}
The output of the program remains the same, so we haven’t shown the resulting output here.
Okay, let’s carry out another exercise. This time you just want to print the name and e-mail
address where the first name matches to “Michael.” See Listing 10-4.
In order to modify the ResultSet and the database, the ResultSet class provides a set of update
methods for each data type. Also, there are other supporting methods such as updateRow() and
deleteRow() to make the task simpler. It’s time to get your hands dirty: assume that one of your contacts
in your addressBook database has changed his phone number, so you are now going to update his
phone number in your database using a JDBC program.
2
НужнаListing
помощь с учебой?
10-5. DbUpdate.java
import java.sql.*;
Наши эксперты
готовы помочь!
// To illustrate how we can update a database
class DbUpdate {
public static void main(String[] args) throws SQLException { try
(Connection connection = DbConnector connectToDb();
(Connection connection = DbConnector.connectToDb();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM
contact WHERE firstName=\"Michael\"")) {
// first fetch the data and display it before the update operation
System.out.println("Before the update");
System.out.println("id \tfName \tlName \temail \t\tphoneNo");
while (resultSet.next()) {
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo"));
}
// now update the resultSet and display the modified data
resultSet.absolute(1);
resultSet.updateString("phoneNo", "+919976543210");
System.out.println("After the update"); System.out.println("id
\tfName \tlName \temail \t\tphoneNo"); resultSet.beforeFirst();
while (resultSet.next()) {
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo"));
}
293
Well, that looks straightforward. Now, execute it and see what this program prints:
Good, the program did not result in any exception. But wait, the phone number of Michael is not
updated! What happened? You forgot a vital statement after the update: the updateRow() method.
Every time you make change in ResultSet using the appropriate updateXXX() method, you need to call
updateRow() to make sure that all the values are actually updated in the database. Make this change
and try again (see Listing 10-6).
294
import java.sql.*;
// To illustrate how we can update a database
class DbUpdate2 {
public static void main(String[] args) throws SQLException { try
(Connection connection = DbConnector.connectToDb();
// create a statement from which the created ResultSets
// are "scroll sensitive" as well as "updatable"
Statement statement =
connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet resultSet = statement.executeQuery("SELECT *
FROM contact WHERE firstName=\"Michael\"")) {
// first fetch the data and display it before the update operation
System.out.println("Before the update");
System.out.println("id \tfName \tlName \temail \t\tphoneNo");
while (resultSet.next()) {
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo"));
}
// now update the resultSet and display the modified data
resultSet.absolute(1);
resultSet.updateString("phoneNo", "+919976543210");
// reflect those changes back to the database by calling updateRow() method
resultSet.updateRow();
System.out.println("After the update"); System.out.println("id
\tfName \tlName \temail \t\tphoneNo"); resultSet.beforeFirst();
while (resultSet.next()) {
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo")); 2
Нужна помощь с учебой? }
} catch (SQLException e) {
e.printStackTrace();
Наши эксперты готовы помочь! }
System.exit(−1);
}
}
Now this program prints the following:
295
Yes, it is working fine now. Now you know the requirements and steps required to update a row in a database.
Always call updateRow() after modifying the row contents; otherwise you will lose the changes.
Next, how about inserting a record in the RecordSet and the database? Try the next example, shown in Listing
10-7.
import java.sql.*;
// To illustrate how to insert a row in a ResultSet and in the database class
DbInsert {
while (resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo"));
}
296
What happened in this example? After printing the current records, you call the
moveToInsertRow() method. This method sets the cursor to a new record and prepares the ResultSet
for the insertion of a row (creates a buffer to hold the column values). After it, you use the
updateString() method to modify each column value in the newly added row. And finally, you call
insertRow() to finally insert the new row into the ResultSet and the database.
One important thing to note here is that you need to provide correct types of values for each column.
Also, you cannot leave a column blank (i.e., not provide any value) if the column value can not be left
unfilled. In both of these violations, you may get a SQLException.
Let’s see what this program prints.
Looks good! Now let’s try another operation: delete a record from the database. Take a look at
the program in Listing 10-8.
import java.sql.*;
// To illustrate how to delete a row in a ResultSet and in the database class
DbDelete {
297
This program simply selects a proper row to delete and calls the deleteRow() method on the
current selected row. Here’s the output of the program:
Well, the program works fine and correctly removes the row where the first name of the
person is “John.” You might have remembered that you have created a table named contact
in your database to work with.
At that time, you created that table from the MySQL command prompt. The same task could have been
done through a JDBC program. At this juncture, let’s create a new table named familyGroup in the
database programmatically (see Listing 10-9). You will use this table later in this chapter.
import java.sql.*;
class DbCreateTable {
public static void main(String[] args) {
try (Connection connection = DbConnector.connectToDb();
Statement statement = connection.createStatement()){
// use CREATE TABLE SQL statement to create table familyGroup
int result = statement.executeUpdate("CREATE TABLE familyGroup (id int not
null auto_increment, nickName varchar(30) not null, primary key(id));");
System.out.println("Table created successfully");
}
catch (SQLException sqle) {
sqle.printStackTrace();
System.exit(−1);
}
}
}
298
<< < 77 78 79 80 81 82 83 84 85
< Предыдущая 86 87 88 89 90 91 92 93 94 95 96 Следующая >
97 98 > >>
2
Нужна помощь с учебой?
Наши эксперты готовы помочь!