package icse.demo.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/*
 * Code examples are adapted from:
 * https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
 * and
 * https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html
 */
public class SqlDatabaseConnectionDemo
{

    public static void main(String[] args)
    {
        try (Connection connection = createConnection();)
        {
            viewTable(connection);
            float percentage = 80;
            modifyPrices(percentage, connection);
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static Connection createConnection()
    {
        try
        {
            String connectionUrl = "jdbc:mysql://localhost:8008/database1";
            Connection connection = DriverManager.getConnection(connectionUrl);
            return connection;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * This method prints the content of the "coffees" table in the console.
     * 
     * @param connection
     *            the connection to the database
     */
    public static void viewTable(Connection connection)
    {
        String query = "SELECT cof_name, sup_id, price, sales, total FROM coffees;";
        try (Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery(query);)
        {
            while (rs.next())
            {
                String coffeeName = rs.getString("cof_name");
                int supplierID = rs.getInt("sup_id");
                float price = rs.getFloat("price");
                int sales = rs.getInt("sales");
                int total = rs.getInt("total");
                System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total);
            }
        }
        catch (SQLException e)
        {
            System.out.println(e);
        }
    }

    /**
     * This method modifies values in the "price" column of the "coffees" table using a percentage parameter.
     * 
     * @param percentage
     *            the value by which to multiply the price. E.g., 80.0 multiplies the price by 80% (i.e., reduces the
     *            price by 20%)
     * @param connection
     *            the database connection
     */
    public static void modifyPrices(float percentage, Connection connection)
    {
        try (Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                ResultSet uprs = stmt.executeQuery("SELECT * FROM coffees;");)
        {
            while (uprs.next())
            {
                float f = uprs.getFloat("price");
                uprs.updateFloat("price", f * percentage);
                uprs.updateRow();
            }
        }
        catch (SQLException e)
        {
            System.out.println(e);
        }
    }
}

Official API Reference

Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace(). The format of this information depends on the implementation, but the following example may be regarded as typical:
 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)
 
This example was produced by running the program:
 class MyClass {
     public static void main(String[] args) {
         crunch(null);
     }
     static void crunch(int[] a) {
         mash(a);
     }
     static void mash(int[] b) {
         System.out.println(b[0]);
     }
 }
 
The backtrace for a throwable with an initialized, non-null cause should generally include the backtrace for the cause. The format of this information depends on the implementation, but the following example may be regarded as typical:
 HighLevelException: MidLevelException: LowLevelException
         at Junk.a(Junk.java:13)
         at Junk.main(Junk.java:4)
 Caused by: MidLevelException: LowLevelException
         at Junk.c(Junk.java:23)
         at Junk.b(Junk.java:17)
         at Junk.a(Junk.java:11)
         ... 1 more
 Caused by: LowLevelException
         at Junk.e(Junk.java:30)
         at Junk.d(Junk.java:27)
         at Junk.c(Junk.java:21)
         ... 3 more
 
Note the presence of lines containing the characters "...". These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught. The above example was produced by running the program:
 public class Junk {
     public static void main(String args[]) {
         try {
             a();
         } catch(HighLevelException e) {
             e.printStackTrace();
         }
     }
     static void a() throws HighLevelException {
         try {
             b();
         } catch(MidLevelException e) {
             throw new HighLevelException(e);
         }
     }
     static void b() throws MidLevelException {
         c();
     }
     static void c() throws MidLevelException {
         try {
             d();
         } catch(LowLevelException e) {
             throw new MidLevelException(e);
         }
     }
     static void d() throws LowLevelException {
        e();
     }
     static void e() throws LowLevelException {
         throw new LowLevelException();
     }
 }

 class HighLevelException extends Exception {
     HighLevelException(Throwable cause) { super(cause); }
 }

 class MidLevelException extends Exception {
     MidLevelException(Throwable cause)  { super(cause); }
 }

 class LowLevelException extends Exception {
 }
 
As of release 7, the platform supports the notion of suppressed exceptions (in conjunction with the try-with-resources statement). Any exceptions that were suppressed in order to deliver an exception are printed out beneath the stack trace. The format of this information depends on the implementation, but the following example may be regarded as typical:
 Exception in thread "main" java.lang.Exception: Something happened
  at Foo.bar(Foo.java:10)
  at Foo.main(Foo.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 0
          at Resource.close(Resource.java:26)
          at Foo.bar(Foo.java:9)
          ... 1 more
 
Note that the "... n more" notation is used on suppressed exceptions just as it is used on causes. Unlike causes, suppressed exceptions are indented beyond their "containing exceptions."

An exception can have both a cause and one or more suppressed exceptions:

 Exception in thread "main" java.lang.Exception: Main block
  at Foo3.main(Foo3.java:7)
  Suppressed: Resource$CloseFailException: Resource ID = 2
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 1
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
 Caused by: java.lang.Exception: I did it
  at Foo3.main(Foo3.java:8)
 
Likewise, a suppressed exception can have a cause:
 Exception in thread "main" java.lang.Exception: Main block
  at Foo4.main(Foo4.java:6)
  Suppressed: Resource2$CloseFailException: Resource ID = 1
          at Resource2.close(Resource2.java:20)
          at Foo4.main(Foo4.java:5)
  Caused by: java.lang.Exception: Rats, you caught me
          at Resource2$CloseFailException.<init>(Resource2.java:45)
          ... 2 more
 

Official API Reference

All Implemented Interfaces:
Serializable, Iterable<Throwable>
Direct Known Subclasses:
BatchUpdateException, RowSetWarning, SerialException, SQLClientInfoException, SQLNonTransientException, SQLRecoverableException, SQLTransientException, SQLWarning, SyncFactoryException, SyncProviderException

An exception that provides information on a database access error or other errors.

Each SQLException provides several kinds of information:

Since:
1.1
See Also:
Serialized Form

Official API Reference

All Superinterfaces:
AutoCloseable, Wrapper

A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

Note: When configuring a Connection, JDBC applications should use the appropriate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection's configuration when there is a JDBC method available. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.

A new Connection object created using the JDBC 2.1 core API has an initially empty type map associated with it. A user may enter a custom mapping for a UDT in this type map. When a UDT is retrieved from a data source with the method ResultSet.getObject, the getObject method will check the connection's type map to see if there is an entry for that UDT. If so, the getObject method will map the UDT to the class indicated. If there is no entry, the UDT will be mapped using the standard mapping.

A user may create a new type map, which is a java.util.Map object, make an entry in it, and pass it to the java.sql methods that can perform custom mapping. In this case, the method will use the given type map instead of the one associated with the connection.

For example, the following code fragment specifies that the SQL type ATHLETES will be mapped to the class Athletes in the Java programming language. The code fragment retrieves the type map for the Connection object con, inserts the entry into it, and then sets the type map with the new entry as the connection's type map.

      java.util.Map map = con.getTypeMap();
      map.put("mySchemaName.ATHLETES", Class.forName("Athletes"));
      con.setTypeMap(map);
 

Since:
1.1
See Also:
DriverManager.getConnection(java.lang.String, java.util.Properties), Statement, ResultSet, DatabaseMetaData

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace(). The format of this information depends on the implementation, but the following example may be regarded as typical:
 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)
 
This example was produced by running the program:
 class MyClass {
     public static void main(String[] args) {
         crunch(null);
     }
     static void crunch(int[] a) {
         mash(a);
     }
     static void mash(int[] b) {
         System.out.println(b[0]);
     }
 }
 
The backtrace for a throwable with an initialized, non-null cause should generally include the backtrace for the cause. The format of this information depends on the implementation, but the following example may be regarded as typical:
 HighLevelException: MidLevelException: LowLevelException
         at Junk.a(Junk.java:13)
         at Junk.main(Junk.java:4)
 Caused by: MidLevelException: LowLevelException
         at Junk.c(Junk.java:23)
         at Junk.b(Junk.java:17)
         at Junk.a(Junk.java:11)
         ... 1 more
 Caused by: LowLevelException
         at Junk.e(Junk.java:30)
         at Junk.d(Junk.java:27)
         at Junk.c(Junk.java:21)
         ... 3 more
 
Note the presence of lines containing the characters "...". These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught. The above example was produced by running the program:
 public class Junk {
     public static void main(String args[]) {
         try {
             a();
         } catch(HighLevelException e) {
             e.printStackTrace();
         }
     }
     static void a() throws HighLevelException {
         try {
             b();
         } catch(MidLevelException e) {
             throw new HighLevelException(e);
         }
     }
     static void b() throws MidLevelException {
         c();
     }
     static void c() throws MidLevelException {
         try {
             d();
         } catch(LowLevelException e) {
             throw new MidLevelException(e);
         }
     }
     static void d() throws LowLevelException {
        e();
     }
     static void e() throws LowLevelException {
         throw new LowLevelException();
     }
 }

 class HighLevelException extends Exception {
     HighLevelException(Throwable cause) { super(cause); }
 }

 class MidLevelException extends Exception {
     MidLevelException(Throwable cause)  { super(cause); }
 }

 class LowLevelException extends Exception {
 }
 
As of release 7, the platform supports the notion of suppressed exceptions (in conjunction with the try-with-resources statement). Any exceptions that were suppressed in order to deliver an exception are printed out beneath the stack trace. The format of this information depends on the implementation, but the following example may be regarded as typical:
 Exception in thread "main" java.lang.Exception: Something happened
  at Foo.bar(Foo.java:10)
  at Foo.main(Foo.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 0
          at Resource.close(Resource.java:26)
          at Foo.bar(Foo.java:9)
          ... 1 more
 
Note that the "... n more" notation is used on suppressed exceptions just as it is used on causes. Unlike causes, suppressed exceptions are indented beyond their "containing exceptions."

An exception can have both a cause and one or more suppressed exceptions:

 Exception in thread "main" java.lang.Exception: Main block
  at Foo3.main(Foo3.java:7)
  Suppressed: Resource$CloseFailException: Resource ID = 2
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
  Suppressed: Resource$CloseFailException: Resource ID = 1
          at Resource.close(Resource.java:26)
          at Foo3.main(Foo3.java:5)
 Caused by: java.lang.Exception: I did it
  at Foo3.main(Foo3.java:8)
 
Likewise, a suppressed exception can have a cause:
 Exception in thread "main" java.lang.Exception: Main block
  at Foo4.main(Foo4.java:6)
  Suppressed: Resource2$CloseFailException: Resource ID = 1
          at Resource2.close(Resource2.java:20)
          at Foo4.main(Foo4.java:5)
  Caused by: java.lang.Exception: Rats, you caught me
          at Resource2$CloseFailException.<init>(Resource2.java:45)
          ... 2 more
 

Official API Reference

All Implemented Interfaces:
Serializable, Iterable<Throwable>
Direct Known Subclasses:
BatchUpdateException, RowSetWarning, SerialException, SQLClientInfoException, SQLNonTransientException, SQLRecoverableException, SQLTransientException, SQLWarning, SyncFactoryException, SyncProviderException

An exception that provides information on a database access error or other errors.

Each SQLException provides several kinds of information:

Since:
1.1
See Also:
Serialized Form

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

All Superinterfaces:
AutoCloseable, Wrapper

A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

Note: When configuring a Connection, JDBC applications should use the appropriate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection's configuration when there is a JDBC method available. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.

A new Connection object created using the JDBC 2.1 core API has an initially empty type map associated with it. A user may enter a custom mapping for a UDT in this type map. When a UDT is retrieved from a data source with the method ResultSet.getObject, the getObject method will check the connection's type map to see if there is an entry for that UDT. If so, the getObject method will map the UDT to the class indicated. If there is no entry, the UDT will be mapped using the standard mapping.

A user may create a new type map, which is a java.util.Map object, make an entry in it, and pass it to the java.sql methods that can perform custom mapping. In this case, the method will use the given type map instead of the one associated with the connection.

For example, the following code fragment specifies that the SQL type ATHLETES will be mapped to the class Athletes in the Java programming language. The code fragment retrieves the type map for the Connection object con, inserts the entry into it, and then sets the type map with the new entry as the connection's type map.

      java.util.Map map = con.getTypeMap();
      map.put("mySchemaName.ATHLETES", Class.forName("Athletes"));
      con.setTypeMap(map);
 

Since:
1.1
See Also:
DriverManager.getConnection(java.lang.String, java.util.Properties), Statement, ResultSet, DatabaseMetaData

Official API Reference

All Superinterfaces:
AutoCloseable, Wrapper

A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

Note: When configuring a Connection, JDBC applications should use the appropriate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection's configuration when there is a JDBC method available. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.

A new Connection object created using the JDBC 2.1 core API has an initially empty type map associated with it. A user may enter a custom mapping for a UDT in this type map. When a UDT is retrieved from a data source with the method ResultSet.getObject, the getObject method will check the connection's type map to see if there is an entry for that UDT. If so, the getObject method will map the UDT to the class indicated. If there is no entry, the UDT will be mapped using the standard mapping.

A user may create a new type map, which is a java.util.Map object, make an entry in it, and pass it to the java.sql methods that can perform custom mapping. In this case, the method will use the given type map instead of the one associated with the connection.

For example, the following code fragment specifies that the SQL type ATHLETES will be mapped to the class Athletes in the Java programming language. The code fragment retrieves the type map for the Connection object con, inserts the entry into it, and then sets the type map with the new entry as the connection's type map.

      java.util.Map map = con.getTypeMap();
      map.put("mySchemaName.ATHLETES", Class.forName("Athletes"));
      con.setTypeMap(map);
 

Since:
1.1
See Also:
DriverManager.getConnection(java.lang.String, java.util.Properties), Statement, ResultSet, DatabaseMetaData

Official API Reference

All Superinterfaces:
AutoCloseable, Wrapper

A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

Note: When configuring a Connection, JDBC applications should use the appropriate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection's configuration when there is a JDBC method available. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.

A new Connection object created using the JDBC 2.1 core API has an initially empty type map associated with it. A user may enter a custom mapping for a UDT in this type map. When a UDT is retrieved from a data source with the method ResultSet.getObject, the getObject method will check the connection's type map to see if there is an entry for that UDT. If so, the getObject method will map the UDT to the class indicated. If there is no entry, the UDT will be mapped using the standard mapping.

A user may create a new type map, which is a java.util.Map object, make an entry in it, and pass it to the java.sql methods that can perform custom mapping. In this case, the method will use the given type map instead of the one associated with the connection.

For example, the following code fragment specifies that the SQL type ATHLETES will be mapped to the class Athletes in the Java programming language. The code fragment retrieves the type map for the Connection object con, inserts the entry into it, and then sets the type map with the new entry as the connection's type map.

      java.util.Map map = con.getTypeMap();
      map.put("mySchemaName.ATHLETES", Class.forName("Athletes"));
      con.setTypeMap(map);
 

Since:
1.1
See Also:
DriverManager.getConnection(java.lang.String, java.util.Properties), Statement, ResultSet, DatabaseMetaData

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
Parameters:
x - The Object to be printed.

Official API Reference

All Implemented Interfaces:
Serializable, Iterable<Throwable>
Direct Known Subclasses:
BatchUpdateException, RowSetWarning, SerialException, SQLClientInfoException, SQLNonTransientException, SQLRecoverableException, SQLTransientException, SQLWarning, SyncFactoryException, SyncProviderException

An exception that provides information on a database access error or other errors.

Each SQLException provides several kinds of information:

Since:
1.1
See Also:
Serialized Form

Official API Reference

Creates a Statement object for sending SQL statements to the database. SQL statements without parameters are normally executed using Statement objects. If the same SQL statement is executed many times, it may be more efficient to use a PreparedStatement object.

Result sets created using the returned Statement object will by default be type TYPE_FORWARD_ONLY and have a concurrency level of CONCUR_READ_ONLY. The holdability of the created result sets can be determined by calling getHoldability().

Returns:
a new default Statement object
Throws:
SQLException - if a database access error occurs or this method is called on a closed connection

Official API Reference

All Superinterfaces:
AutoCloseable, Wrapper
All Known Subinterfaces:
CallableStatement, PreparedStatement

The object used for executing a static SQL statement and returning the results it produces.

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a current ResultSet object of the statement if an open one exists.

Since:
1.1
See Also:
Connection.createStatement(), ResultSet

Official API Reference

Executes the given SQL statement, which returns a single ResultSet object.

Note:This method cannot be called on a PreparedStatement or CallableStatement.

Parameters:
sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement
Returns:
a ResultSet object that contains the data produced by the given query; never null
Throws:
SQLException - if a database access error occurs, this method is called on a closed Statement, the given SQL statement produces anything other than a single ResultSet object, the method is called on a PreparedStatement or CallableStatement
SQLTimeoutException - when the driver has determined that the timeout value that was specified by the setQueryTimeout method has been exceeded and has at least attempted to cancel the currently running Statement

Official API Reference

Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.
Parameters:
columnLabel - the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
Returns:
the column value; if the value is SQL NULL, the value returned is null
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set

Official API Reference

All Implemented Interfaces:
Serializable, CharSequence, Comparable<String>, Constable, ConstantDesc
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

     String str = "abc";
 

is equivalent to:

     char data[] = {'a', 'b', 'c'};
     String str = new String(data);
 

Here are some more examples of how strings can be used:

     System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2, 3);
     String d = cde.substring(1, 2);
 

The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String.

The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).

Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.

Implementation Note:
The implementation of the string concatenation operator is left to the discretion of a Java compiler, as long as the compiler ultimately conforms to The Java Language Specification. For example, the javac compiler may implement the operator with StringBuffer, StringBuilder, or java.lang.invoke.StringConcatFactory depending on the JDK version. The implementation of string conversion is typically through the method toString, defined by Object and inherited by all classes in Java.
See Java Language Specification:
15.18.1 String Concatenation Operator +
Since:
1.0
See Also:
Object.toString(), StringBuffer, StringBuilder, Charset, Serialized Form

Official API Reference

Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language.
Parameters:
columnLabel - the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
Returns:
the column value; if the value is SQL NULL, the value returned is 0
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set

Official API Reference

Retrieves the value of the designated column in the current row of this ResultSet object as a float in the Java programming language.
Parameters:
columnLabel - the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
Returns:
the column value; if the value is SQL NULL, the value returned is 0
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set

Official API Reference

Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language.
Parameters:
columnLabel - the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
Returns:
the column value; if the value is SQL NULL, the value returned is 0
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set

Official API Reference

Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language.
Parameters:
columnLabel - the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
Returns:
the column value; if the value is SQL NULL, the value returned is 0
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
Parameters:
x - The String to be printed.

Official API Reference

All Superinterfaces:
AutoCloseable, Wrapper

A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

Note: When configuring a Connection, JDBC applications should use the appropriate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection's configuration when there is a JDBC method available. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.

A new Connection object created using the JDBC 2.1 core API has an initially empty type map associated with it. A user may enter a custom mapping for a UDT in this type map. When a UDT is retrieved from a data source with the method ResultSet.getObject, the getObject method will check the connection's type map to see if there is an entry for that UDT. If so, the getObject method will map the UDT to the class indicated. If there is no entry, the UDT will be mapped using the standard mapping.

A user may create a new type map, which is a java.util.Map object, make an entry in it, and pass it to the java.sql methods that can perform custom mapping. In this case, the method will use the given type map instead of the one associated with the connection.

For example, the following code fragment specifies that the SQL type ATHLETES will be mapped to the class Athletes in the Java programming language. The code fragment retrieves the type map for the Connection object con, inserts the entry into it, and then sets the type map with the new entry as the connection's type map.

      java.util.Map map = con.getTypeMap();
      map.put("mySchemaName.ATHLETES", Class.forName("Athletes"));
      con.setTypeMap(map);
 

Since:
1.1
See Also:
DriverManager.getConnection(java.lang.String, java.util.Properties), Statement, ResultSet, DatabaseMetaData

Official API Reference

The System class contains several useful class fields and methods. It cannot be instantiated. Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
1.0

Official API Reference

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
Parameters:
x - The Object to be printed.

Official API Reference

All Implemented Interfaces:
Serializable, Iterable<Throwable>
Direct Known Subclasses:
BatchUpdateException, RowSetWarning, SerialException, SQLClientInfoException, SQLNonTransientException, SQLRecoverableException, SQLTransientException, SQLWarning, SyncFactoryException, SyncProviderException

An exception that provides information on a database access error or other errors.

Each SQLException provides several kinds of information:

Since:
1.1
See Also:
Serialized Form

Official API Reference

Creates a Statement object that will generate ResultSet objects with the given type and concurrency. This method is the same as the createStatement method above, but it allows the default result set type and concurrency to be overridden. The holdability of the created result sets can be determined by calling getHoldability().
Parameters:
resultSetType - a result set type; one of ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE
resultSetConcurrency - a concurrency type; one of ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE
Returns:
a new Statement object that will generate ResultSet objects with the given type and concurrency
Throws:
SQLException - if a database access error occurs, this method is called on a closed connection or the given parameters are not ResultSet constants indicating type and concurrency
SQLFeatureNotSupportedException - if the JDBC driver does not support this method or this method is not supported for the specified result set type and result set concurrency.
Since:
1.2

Official API Reference

All Superinterfaces:
AutoCloseable, Wrapper
All Known Subinterfaces:
CallableStatement, PreparedStatement

The object used for executing a static SQL statement and returning the results it produces.

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a current ResultSet object of the statement if an open one exists.

Since:
1.1
See Also:
Connection.createStatement(), ResultSet

Official API Reference

Executes the given SQL statement, which returns a single ResultSet object.

Note:This method cannot be called on a PreparedStatement or CallableStatement.

Parameters:
sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement
Returns:
a ResultSet object that contains the data produced by the given query; never null
Throws:
SQLException - if a database access error occurs, this method is called on a closed Statement, the given SQL statement produces anything other than a single ResultSet object, the method is called on a PreparedStatement or CallableStatement
SQLTimeoutException - when the driver has determined that the timeout value that was specified by the setQueryTimeout method has been exceeded and has at least attempted to cancel the currently running Statement

Official API Reference

Retrieves the value of the designated column in the current row of this ResultSet object as a float in the Java programming language.
Parameters:
columnLabel - the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
Returns:
the column value; if the value is SQL NULL, the value returned is 0
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set

Official API Reference

Updates the designated column with a float value. The updater methods are used to update column values in the current row or the insert row. The updater methods do not update the underlying database; instead the updateRow or insertRow methods are called to update the database.
Parameters:
columnLabel - the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column
x - the new column value
Throws:
SQLException - if the columnLabel is not valid; if a database access error occurs; the result set concurrency is CONCUR_READ_ONLY or this method is called on a closed result set
SQLFeatureNotSupportedException - if the JDBC driver does not support this method
Since:
1.2

Official API Reference

All Superinterfaces:
AutoCloseable, Wrapper

A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.

A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

Note: When configuring a Connection, JDBC applications should use the appropriate Connection method such as setAutoCommit or setTransactionIsolation. Applications should not invoke SQL commands directly to change the connection's configuration when there is a JDBC method available. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved.

A new Connection object created using the JDBC 2.1 core API has an initially empty type map associated with it. A user may enter a custom mapping for a UDT in this type map. When a UDT is retrieved from a data source with the method ResultSet.getObject, the getObject method will check the connection's type map to see if there is an entry for that UDT. If so, the getObject method will map the UDT to the class indicated. If there is no entry, the UDT will be mapped using the standard mapping.

A user may create a new type map, which is a java.util.Map object, make an entry in it, and pass it to the java.sql methods that can perform custom mapping. In this case, the method will use the given type map instead of the one associated with the connection.

For example, the following code fragment specifies that the SQL type ATHLETES will be mapped to the class Athletes in the Java programming language. The code fragment retrieves the type map for the Connection object con, inserts the entry into it, and then sets the type map with the new entry as the connection's type map.

      java.util.Map map = con.getTypeMap();
      map.put("mySchemaName.ATHLETES", Class.forName("Athletes"));
      con.setTypeMap(map);
 

Since:
1.1
See Also:
DriverManager.getConnection(java.lang.String, java.util.Properties), Statement, ResultSet, DatabaseMetaData

This program showcases how to do 3 things with the JDBC API:

  1. Connect to an SQL database.
  2. Read values from a table of the database.
  3. Update some values in a table.

The general format of connection URLs is protocol:subprotocol:subname, where

The exact format of the subprotocol and subname components is defined by each database provider. Popular database systems include: MySQL (the database system in this example), SQLite, and PostgreSQL.

To see details about connection URLs for other common databases, see this codejava tutorial.

Reference

The basic format of connecting to a MySQL database is jdbc:mysql://[host][:port]/[database], whereby host represents an IP address or host name on which the server is running. In our code example, the host is localhost, 8008 is the port number and database1 is the database name.

Reference

The basic format of connecting to a SQLite database is jdbc:sqlite:[database_file_path], whereby database_file_path represents a relative or absolute path of the target SQLite database. For example, jdbc:sqlite:c:/User/Documents/database1.db connects to database database1.db specified by an absolute path.

Reference

The basic format of connecting to a PostgreSQL database is jdbc:postgresql://[host][:port]/[database], whereby host represents an IP address or host name on which the server is running (optional, defaults to localhost), port is the port number (optional, defaults to 5432), and database is the database name. For example, jdbc:postgresql://localhost/ProductDB connects to the ProductDB on PostgreSQL server on the host localhost.

Reference

JDBC Driver is a software component that enables java application to interact with the database.

Reference

The SELECT statement is used to get data from an SQL database. Its syntax is as follows:

SELECT columnA, columnB, ... FROM table_name;

To select all columns at once, * can be used instead of listing each column, like so:

SELECT * FROM table_name;

In our case, we only want to select columns cof_name, sup_id, price, sales, total from the coffees table.

The cursor in a ResultSet initially points before the first row. Calling next() moves the cursor to the next row in the set, returning false when there are no longer any rows left.

Using a while loop is therefore an efficient way of looping through all of the data in a ResultSet, as seen in the given code example.

The iterator design pattern is used to provide access to a collection of objects encapsulated within another object without violating encapsulation and information hiding properties of this object.

In the case of ResultSet, it has a cursor pointing to a row of data. With each call to next(), the cursor moves down one row. This is how data encapsulated within ResultSet is obtained using the iterator design pattern.

The idea of information hiding and encapsulation of structures is to only reveal the minimum amount of information that is necessary to use them, and hide the rest.

getXXX() should be consistent with the data type of the SQL table column. If not, it will throw an exception.

For instance, let's say column "sup_id" is actually of type VARCHAR. getInt("sup_id") would then be an inappropriate call.

VARCHAR, or Variable Character, is a variable length string.

The maximum length of String values in a VARCHAR column can be defined in parentheses when declaring the column type. For example, VARCHAR(500) can contain a maximum of 500 characters.

Reference

The try-with-resources statement ensures that each resource is closed at the end of the statement execution.

Reference

A resource is an object that must be closed once your program is done using it. If we don't close the resources, it may constitute a resource leak and also the program could exhaust the resources available to it.

Reference

You can pass any object as a resource that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable.

This method retrieves the contents of the coffees tables and prints them.

Step-by-step:

The overall approach in this method is:

  1. Creating Statement object by calling createStatement() on Connection object
  2. Creating a ResultSet by calling executeQuery() on Statement object
  3. Iterating through the ResultSet to obtain values in each row

The cursor in a ResultSet initially points before the first row. Calling next() moves the cursor to the next row in the set, returning false when there are no longer any rows left.

Using a while loop is therefore an efficient way of looping through all of the data in a ResultSet, as seen in the given code example.

The iterator design pattern is used to provide access to a collection of objects encapsulated within another object without violating encapsulation and information hiding properties of this object.

In the case of ResultSet, it has a cursor pointing to a row of data. With each call to next(), the cursor moves down one row. This is how data encapsulated within ResultSet is obtained using the iterator design pattern.

The idea of information hiding and encapsulation of structures is to only reveal the minimum amount of information that is necessary to use them, and hide the rest.

Reference

The SELECT statement is used to get data from an SQL database. To select all columns at once, * can be used instead of listing each column, like so:

SELECT * FROM table_name;

In our case, we want to select all columns from the coffees table.

This constant indicates a scrollable ResultSet, meaning its cursor can move both forward and backward relative to the current position, and it can move to an absolute position. TYPE_SCROLL_SENSITIVE also makes ResultSet data sensitive to changes made to the database.

Taken from tutorialspoint: "(Sensitivity) means if we have established a connection with a database using a JDBC program and retrieved a ResultSet holding all the records in a table named SampleTable. Meanwhile, if we have added some more records to the table (after retrieving the ResultSet), these recent changes will be reflected in the ResultSet object we previously obtained."

This constant indicates that the concurrency mode for this ResultSet object is updatable. This means that once you get a ResultSet object you can update its contents, which is particularly important for the task we are trying to complete since the goal is to update values in the ResultSet.

Reference

The try-with-resources statement ensures that each resource is closed at the end of the statement execution.

Reference

A resource is an object that must be closed once your program is done using it. If we don't close the resources, it may constitute a resource leak and also the program could exhaust the resources available to it.

Reference

You can pass any object as a resource that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable.


💡updateRow

Per protocol, updateRow() must be called after updateFloat in order to change the underlying database.

void updateRow() throws SQLException

Official API Reference

Updates the underlying database with the new contents of the current row of this ResultSet object. This method cannot be called when the cursor is on the insert row.
Throws:
SQLException - if a database access error occurs; the result set concurrency is CONCUR_READ_ONLY; this method is called on a closed result set or if this method is called when the cursor is on the insert row
SQLFeatureNotSupportedException - if the JDBC driver does not support this method
Since:
1.2



💡next

This method both checks if there is another row, returning true or false accordingly, and advances the cursor.

boolean next() throws SQLException

Official API Reference

Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.

If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.

Returns:
true if the new current row is valid; false if there are no more rows
Throws:
SQLException - if a database access error occurs or this method is called on a closed result set



💡ResultSet

ResultSet maintains a cursor which points to the current row in the data. This is how we are able to traverse and obtain each row.

We can also think of ResultSet objects as iterators. While ResultSet does not implement the Iterable interface, it follows an iterator design pattern.

public interface ResultSet extends Wrapper, AutoCloseable

Official API Reference

All Superinterfaces:
AutoCloseable, Wrapper
All Known Subinterfaces:
CachedRowSet, FilteredRowSet, JdbcRowSet, JoinRowSet, RowSet, SyncResolver, WebRowSet
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.

A ResultSet object maintains a pointing to its current row of data. Initially the is positioned before the first row. The next method moves the to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

A default ResultSet object is not updatable and has a that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. The following code fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by others, and that is updatable. See ResultSet fields for other options.

       Statement stmt = con.createStatement(
                                      ResultSet.TYPE_SCROLL_INSENSITIVE,
                                      ResultSet.CONCUR_UPDATABLE);
       ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
       // rs will be scrollable, will not show changes made by others,
       // and will be updatable

 
The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1. For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once.

For the getter methods, a JDBC driver attempts to convert the underlying data to the Java type specified in the getter method and returns a suitable Java value. The JDBC specification has a table showing the allowable mappings from SQL types to Java types that can be used by the ResultSet getter methods.

Column names used as input to getter methods are case insensitive. When a getter method is called with a column name and several columns have the same name, the value of the first matching column will be returned. The column name option is designed to be used when column names are used in the SQL query that generated the result set. For columns that are NOT explicitly named in the query, it is best to use column numbers. If column names are used, the programmer should take care to guarantee that they uniquely refer to the intended columns, which can be assured with the SQL AS clause.

A set of updater methods were added to this interface in the JDBC 2.0 API (Java 2 SDK, Standard Edition, version 1.2). The comments regarding parameters to the getter methods also apply to parameters to the updater methods.

The updater methods may be used in two ways:

  1. to update a column value in the current row. In a scrollable ResultSet object, the can be moved backwards and forwards, to an absolute position, or to a position relative to the current row. The following code fragment updates the NAME column in the fifth row of the ResultSet object rs and then uses the method updateRow to update the data source table from which rs was derived.
           rs.absolute(5); // moves the  to the fifth row of rs
           rs.updateString("NAME", "AINSWORTH"); // updates the
              // NAME column of row 5 to be AINSWORTH
           rs.updateRow(); // updates the row in the data source
    
     
  2. to insert column values into the insert row. An updatable ResultSet object has a special row associated with it that serves as a staging area for building a row to be inserted. The following code fragment moves the to the insert row, builds a three-column row, and inserts it into rs and into the data source table using the method insertRow.
           rs.moveToInsertRow(); // moves  to the insert row
           rs.updateString(1, "AINSWORTH"); // updates the
              // first column of the insert row to be AINSWORTH
           rs.updateInt(2,35); // updates the second column to be 35
           rs.updateBoolean(3, true); // updates the third column to true
           rs.insertRow();
           rs.moveToCurrentRow();
    
     

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

The number, types and properties of a ResultSet object's columns are provided by the ResultSetMetaData object returned by the ResultSet.getMetaData method.

Since:
1.1
See Also:
Statement.executeQuery(java.lang.String), Statement.getResultSet(), ResultSetMetaData



💡next

This method both checks if there is another row, returning true or false accordingly, and advances the cursor.

boolean next() throws SQLException

Official API Reference

Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.

If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.

Returns:
true if the new current row is valid; false if there are no more rows
Throws:
SQLException - if a database access error occurs or this method is called on a closed result set



💡ResultSet

ResultSet maintains a cursor which points to the current row in the data. This is how we are able to traverse and obtain each row.

We can also think of ResultSet objects as iterators. While ResultSet does not implement the Iterable interface, it follows an iterator design pattern.

public interface ResultSet extends Wrapper, AutoCloseable

Official API Reference

All Superinterfaces:
AutoCloseable, Wrapper
All Known Subinterfaces:
CachedRowSet, FilteredRowSet, JdbcRowSet, JoinRowSet, RowSet, SyncResolver, WebRowSet
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.

A ResultSet object maintains a pointing to its current row of data. Initially the is positioned before the first row. The next method moves the to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

A default ResultSet object is not updatable and has a that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. The following code fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by others, and that is updatable. See ResultSet fields for other options.

       Statement stmt = con.createStatement(
                                      ResultSet.TYPE_SCROLL_INSENSITIVE,
                                      ResultSet.CONCUR_UPDATABLE);
       ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
       // rs will be scrollable, will not show changes made by others,
       // and will be updatable

 
The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1. For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once.

For the getter methods, a JDBC driver attempts to convert the underlying data to the Java type specified in the getter method and returns a suitable Java value. The JDBC specification has a table showing the allowable mappings from SQL types to Java types that can be used by the ResultSet getter methods.

Column names used as input to getter methods are case insensitive. When a getter method is called with a column name and several columns have the same name, the value of the first matching column will be returned. The column name option is designed to be used when column names are used in the SQL query that generated the result set. For columns that are NOT explicitly named in the query, it is best to use column numbers. If column names are used, the programmer should take care to guarantee that they uniquely refer to the intended columns, which can be assured with the SQL AS clause.

A set of updater methods were added to this interface in the JDBC 2.0 API (Java 2 SDK, Standard Edition, version 1.2). The comments regarding parameters to the getter methods also apply to parameters to the updater methods.

The updater methods may be used in two ways:

  1. to update a column value in the current row. In a scrollable ResultSet object, the can be moved backwards and forwards, to an absolute position, or to a position relative to the current row. The following code fragment updates the NAME column in the fifth row of the ResultSet object rs and then uses the method updateRow to update the data source table from which rs was derived.
           rs.absolute(5); // moves the  to the fifth row of rs
           rs.updateString("NAME", "AINSWORTH"); // updates the
              // NAME column of row 5 to be AINSWORTH
           rs.updateRow(); // updates the row in the data source
    
     
  2. to insert column values into the insert row. An updatable ResultSet object has a special row associated with it that serves as a staging area for building a row to be inserted. The following code fragment moves the to the insert row, builds a three-column row, and inserts it into rs and into the data source table using the method insertRow.
           rs.moveToInsertRow(); // moves  to the insert row
           rs.updateString(1, "AINSWORTH"); // updates the
              // first column of the insert row to be AINSWORTH
           rs.updateInt(2,35); // updates the second column to be 35
           rs.updateBoolean(3, true); // updates the third column to true
           rs.insertRow();
           rs.moveToCurrentRow();
    
     

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.

The number, types and properties of a ResultSet object's columns are provided by the ResultSetMetaData object returned by the ResultSet.getMetaData method.

Since:
1.1
See Also:
Statement.executeQuery(java.lang.String), Statement.getResultSet(), ResultSetMetaData



💡getConnection

This method establishes a connection to the given database URL and returns it.

public static Connection getConnection(String url) throws SQLException

Official API Reference

Attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.
Parameters:
url - a database url of the form jdbc:subprotocol:subname
Returns:
a connection to the URL
Throws:
SQLException - if a database access error occurs or the url is null
SQLTimeoutException - when the driver has determined that the timeout value specified by the setLoginTimeout method has been exceeded and has at least tried to cancel the current database connection attempt



💡DriverManager

When getConnection is called, DriverManager tries to select a suitable driver from the list of registered JDBC drivers. This is required to then establish a connection with the database specified by connectionUrl.

An alternative is to use a DataSource.

public class DriverManager extends Object

Official API Reference

The basic service for managing a set of .

NOTE: The DataSource interface, provides another way to connect to a data source. The use of a DataSource object is the preferred means of connecting to a data source.

As part of its initialization, the DriverManager class will attempt to load available by using:

Implementation Note:
DriverManager initialization is done lazily and looks up service providers using the thread context class loader. The drivers loaded and available to an application will depend on the thread context class loader of the thread that triggers driver initialization by DriverManager.

When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same class loader as the current application.

Since:
1.1
See Also:
Driver, Connection