JDBC Example

The following Java JDBC database program connects to a database and prints out each of the authors in the pubs database, as well as their year-to-date sales.

import java.sql.*; public class ExampleApplication { public static void main(String[] args) { String connection_string = "jdbc:microsoft:sqlserver://localhost:1433;" + "User=montoyai;Password=12345;DatabaseName=pubs;"; String SQL = "SELECT a.au_lname, a.au_fname, SUM(t.ytd_sales) " + "FROM authors a, titleauthor, titles t " + "WHERE titleauthor.au_id = a.au_id and " + " titleauthor.title_id = t.title_id " + "GROUP BY a.au_lname, a.au_fname " + "ORDER BY 3 DESC"; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); // Create Connection and Connect to the Server connection = DriverManager.getConnection( connection_string ); // Create a Command object for the SQL statement statement = connection.createStatement( ); // Create a Reader for reading the result set resultSet = statement.executeQuery( SQL ); while( resultSet.next( ) ) { // Extract the data from the server and display it String lname = resultSet.getString( 1 ); if( resultSet.wasNull( ) ) lname = "NULL"; String fname = resultSet.getString( 2 ); if( resultSet.wasNull( ) ) fname = "NULL"; String sales = resultSet.getString( 3 ); if( resultSet.wasNull( ) ) sales = "ZERO"; System.out.println( lname + ", " + fname + " has sales of " + sales); } } catch( Exception ...

Get SQL in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.