Java Reference
In-Depth Information
Display 19.14
Updating Rows with the
UPDATE
Statement
(part 2 of 3)
11
public static void
main(String[] args)
12 {
13
try
14 {
15 Class.forName(driver).newInstance();
16 System.out.println("Loaded the embedded driver.");
17 }
18
catch
(Exception err)
19 {
20 System.err.println("Unable to load the embedded
driver.");
21 err.printStackTrace(System.err);
22 System.exit(0);
23 }
24 String dbName = "BookDatabase";
25 Connection conn =
null
;
26
try
27 {
28 System.out.println("Connecting to the database...");
29 conn = DriverManager.getConnection(protocol + dbName);
30 System.out.println("Connected.");
31 System.out.println(
"Enter the ID number of the author to change:");
32 Scanner scan =
new
Scanner(System.in);
33
int
id = scan.nextInt();
34 scan.nextLine();
35 System.out.println("Enter the new URL for this author.");
36 String newURL = scan.nextLine();
Skips the newline left after
nextInt
()
.
37 Statement s = conn.createStatement();
38 s.execute("UPDATE names " +
39 "SET URL = '" + newURL + "' WHERE author_id = "
+ id);
40 System.out.println("URL changed to " + newURL);
41 conn.close();
42 }
43
catch
(SQLException err)
44 {
45 System.err.println("SQL error.");
46 err.printStackTrace(System.err);
47 System.exit(0);
48 }
49 }
50 }