Connecting to Sybase SQL Anywhere Database in Java

Sybase SQL Anywhere is a powerful database server suitable for enterprise applications. It is also a common database backend for Java Web applications.

This article provides a step by step tutorial on connecting and querying data from a Sybase SQL Anywhere database using Java. We will also look at a sample Java class which returns database server date using SQL.

Java platform provides a standardized API interface for connecting to databases known as JDBC (Java Database Connectivity). Applications can use this standard API to connect to any relational database. Database vendors provide specific java library files (drivers) which can connect to their database and expose a standard interface through JDBC.When we write programs, we will be directly using Java JDBC API and under the hood Java will make use the driver library to connect to database and execute SQL commands.

This tutorial is written for Sybase SQL Anywhere 12, Java 1.6 and Sybase JDBC 4.0 driver. You may need different versions of Sybase JDBC drivers for other configurations. However the overall approach remains the same.

Sybase JDBC driver (sajdbc4.jar) is part of Sybase database installation. It is located under the folder C:\Program Files\SQL Anywhere 12\Java in a Windows machine(assuming default installation). Copy sajdbc4.jar to the folder where SybaseExample.java file (see below) is located.

Java Program to Connect to Sybase SQL Anywhere - JDBC 4.0

Since we are using JDBC 4.0, we don't need to specify the driver name using DriverManager.registerDriver. The following Java program connects to Sybase SQL Anywhere 12 database with JDBC 4.0 driver. It then prints the system date received from the database server,

// Example Java Program - Sybase SQL Anywhere 12 Database Connectivity with JDBC 4.0
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SybaseExample {

    public static void main(String[] args) throws SQLException {
        // uid - user id
        // pwd - password
        // eng - Sybase database server name
        // database - sybase database name
        // host - database host machine ip
        String dburl = "jdbc:sqlanywhere:uid=DBA;pwd=DBA;eng=devdb;database=devdb;links=tcpip(host=172.20.20.20)";
        
        // Connect to Sybase Database
        Connection con = DriverManager.getConnection(dburl);
        Statement statement = con.createStatement();

        // We use Sybase specific select getdate() query to return date
        ResultSet rs = statement.executeQuery("SELECT GETDATE()");
        
        
        if (rs.next()) {
            Date currentDate = rs.getDate(1); // get first column returned
            System.out.println("Current Date from Sybase is : "+currentDate);
        }
        rs.close();
        statement.close();
        con.close();
    }
}

In order to compile or run the above program, you need to add sajdbc4.jar to the classpath of your program. If you are using IDE such as NetBeans or Eclipse, you can add sajdbc4.jar as a dependent library and NetBeans/Eclipse will automatically add it to classpath.

If you are running the above program from command line, copy sajdbc4.jar to the folder where the above Java program is located and then compile the file using the following command (this adds sajdbc4.jar to classpath),

javac -classpath ./sajdbc4.jar SybaseExample.java

Run the Java program using the following command (sajdbc4.jar is added to classpath),

java -classpath "./sajdbc4.jar;." SybaseExample

Note that when you are running SybaseExample, you need both the JDCB jar file and the current folder in the classpath. If everything went well, you will see the following output.

Sybase connectivity in Java

Java Program to Connect to Sybase SQL Anywhere 12 Using JDBC 3.0 Driver

If you want to connect to Sybase SQL Anywhere 12 with JDBC 3.0 driver (sajdbc.jar) use the following code. The only additional item in this program is the loading of driver file. Without the driver configuration, you will encounter the following error,

No suitable driver found for jdbc:sqlanywhere

// Example Java Program - Sybase SQL Anywhere 12 Database Connectivity with JDBC 3.0
import java.sql.*;

public class SybaseExample2 {

    public static void main(String[] args) throws Exception {
        DriverManager.registerDriver( (Driver)
                Class.forName( "sybase.jdbc.sqlanywhere.IDriver" ).newInstance() );
        // uid - user id
        // pwd - password
        // eng - Sybase database server name
        // database - sybase database name
        // host - database host machine ip
        
        String dburl = "jdbc:sqlanywhere:uid=DBA;pwd=DBA;eng=devdb;database=devdb;links=tcpip(host=172.20.20.20)";
        
        // Connect to Sybase Database
        Connection con = DriverManager.getConnection(dburl);
        Statement statement = con.createStatement();

        // We use Sybase specific select getdate() query to return date
        ResultSet rs = statement.executeQuery("SELECT GETDATE()");
        
        
        if (rs.next()) {
            Date currentDate = rs.getDate(1); // get first column returned
            System.out.println("Current Date from Sybase is : "+currentDate);
        }
        rs.close();
        statement.close();
        con.close();
    }
}

Finding Perfect Numbers in a Range Using Java

A perfect number is a positive integer that is equal to the sum of its proper divisors excluding itself. For example, 6 is a perfect number since the sum of its divisors (1 + 2 + 3) is equal to 6.

Finding Perfect Numbers in a Range Using Java

The following Java program finds all perfect numbers between two given numbers. The following program prints perfect numbers between 1 and 10000. We iterate through the range of values and then check whether each number is a perfect number or not.

To check whether a number is perfect, we first find all the proper divisors and then add them up. We then check whether it is same as the given number. The first 4 perfect numbers are 6,28,496 and 8128.

import java.io.IOException;

// Finding perfect numbers in a range using Java
public class PerfectNumbersInRange {

    public static void main(String[] args) throws IOException {
        int starting_number = 1;
        int ending_number = 10000;
        System.out.println("Perfect Numbers between "+starting_number+ " and "+ending_number);
        for (int i = starting_number; i <= ending_number; i++) {
            if (isPerfectNumber(i)) {
                System.out.println(i+" is a perfect number");
            } 
        }
    }
    
    /**
     * Checks whether the given number is a perfect number
     * @param number
     * @return 
     */
    public static boolean isPerfectNumber(int number) {
        int sum=0;         
        for(int i=1; i<=number/2; i++) {
            if(number%i == 0) {
                sum += i;
            }
        }
         
        if(sum==number) { 
            return true;
        }else {
            return false;
        }
    }
 
}

Checking Whether a Number is a Perfect Square Number in Java

A number is known as a square number or perfect square if the number is a square of another number. That is an number n is square if it can be expressed as n = a * a where a is an integer. Some examples of perfect numbers (square numbers) are ,

9 = 3 * 3,   25 = 5 * 5, 100 = 10 * 10

An interesting property of square number is that it can only end with 0, 1, 4, 6, 9 or 25.

Java Program to Find Whether a Number is a Perfect Square Number

The following Java program checks whether a given number is a perfect square number or not. We take the square root of the passed in number and then convert it into an integer. Then we take a square of the value to see whether it is same as the number given. If they are same, we got a perfect square number!

// Finding whether a number is a perfect square number in Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PerfectSquareNumber {
    
    public static void main(String[] args) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please enter an integer : ");
        int number = Integer.parseInt(reader.readLine());
        
        int sqrt = (int) Math.sqrt(number);
        if(sqrt*sqrt == number) {
            System.out.println(number+" is a perfect square number!");
        }else {
            System.out.println(number+" is NOT a perfect square number!");
        }
        
    }
}

Find Smallest Number in an Array Using Java

The following Java program prints the smallest number in a given array. This example uses an inline array, however it can be easily changed to a method taking an array as parameter. We loop through the array comparing whether the current smallest number is bigger than the array value. If yes, we replace the current smallest number with the array value. The initial value of the smallest number is set as Integer.MAX_VALUE which is the largest value an integer variable can have!

Find Smallest Number in an Array Using Java

// Java program to find smallest number in an array
public class FindSmallest {
    
    public static void main(String[] args) {
        int[] numbers = {88,33,55,23,64,123};
        int smallest = Integer.MAX_VALUE;
        
        for(int i =0;i<numbers.length;i++) {
            if(smallest > numbers[i]) {
                smallest = numbers[i];
            }
        }
        
        System.out.println("Smallest number in array is : " +smallest);
    }
}

Connecting to Oracle Database in Java

This article is a step by step guide on connecting to an Oracle database from a Java program. The following standalone program demonstrates Oracle database connectivity using JDBC API. In this program we will use the Oracle's built dummy table DUAL to retrieve Oracle's system date.

Java provides a standard interface to connect to databases and it is known as JDBC (Java Database Connectivity). Oracle provides an implementation library of this JDBC interface using which Java programs can connect to a running oracle database instance.

Step 1 : Download Oracle JDBC Drivers

You can download Oracle JDBC drivers from here. Choose the version appropriate for your database version. In this example, I use the Oracle 11g JDBC driver since I connect to Oracle 11g database. There are two versions available for Oracle 11g, ojdbc5.jar (for JDK 1.5) and ojdbc6.jar (for JDK 1.6). Use appropriate version for your Java installation (Oracle now requires online registration for downloading drivers). I use ojdbc6.jar for this tutorial.

Step 2 : Java Program to Connect to Oracle

The following Java program uses Oracle JDBC driver to connect to a running Oracle database instance. You can use this program on any Oracle database as this example uses Oracle's built-in dummy table DUAL for fetching system date. DUAL enables us to get values such as system date using a normal SQL query.

// Example Java Program - Oracle Database Connectivity
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class OracleSample {

    public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";
    public static final String DBUSER = "system";
    public static final String DBPASS = "manager";

    public static void main(String[] args) throws SQLException {
        
        // Load Oracle JDBC Driver
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        
        // Connect to Oracle Database
        Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);

        Statement statement = con.createStatement();

        // Execute a SELECT query on Oracle Dummy DUAL Table. Useful for retrieving system values
        // Enables us to retrieve values as if querying from a table
        ResultSet rs = statement.executeQuery("SELECT SYSDATE FROM DUAL");
        
        
        if (rs.next()) {
            Date currentDate = rs.getDate(1); // get first column returned
            System.out.println("Current Date from Oracle is : "+currentDate);
        }
        rs.close();
        statement.close();
        con.close();
    }
}

Before you run the program ensure that you change the values for DBURL, DBUSER and DBPASS. DBURL is of the form,

jdbc:oracle:thin:@machinename:1521:databasename

Replace machinename with the name of the machine where oracle is running and replace databasename with service name of the database instance.

See this page for more details on JDBC API.

Step 3 : Add ojdbc.jar to Classpath

In order to compile or run the above program, you need to add ojdbc.jar to the classpath of your program. If you are using IDE such as NetBeans or Eclipse, you can add ojdbc.jar as a dependent library and NetBeans will automatically add it to classpath.

If you are running the above program from command line, copy ojdbc.jar to the folder where the above Java program is located and then compile the file using the following command (this adds ojdbc.jar to classpath),

javac -classpath ./ojdbc6.jar OracleSample.java

Run the Java program using the following command (ojdbc.jar is added to classpath),

java -classpath "./ojdbc6.jar;." OracleSample

Note that when you are running OracleSample, you need both the JDCB jar file and the current folder in the classpath. If everything went well, you will see the following output.

Connecting to Oracle database using Java - Example

If you don't have an oracle instance for testing this program, you can download the free Oracle 11g Express edition from here.