/*
Przygotowanie bazy danych:

drop table Names;
create table Names ( id int primary key, name varchar(20) );

begin
  insert into Names values( 1, 'Asia' );
  insert into Names values( 2, 'Basia' );
  insert into Names values( 3, 'Kasia' );
  insert into Names values( 4, null );
end;

select * from Names;
 */

import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;

public class PobierzDane2 {

    /**
	 * @param args
	 */
    public static void main(String[] args) throws ClassNotFoundException {
        Connection connection = null;
        ;
        Statement stmt = null;
        try {
        	SQLServerDataSource ds = new SQLServerDataSource();
			ds.setServerName("localhost");
			ds.setPortNumber(1433); 
			ds.setUser( "sa" );
			ds.setPassword("sql2005");
			ds.setDatabaseName("KursBD");
			connection = ds.getConnection();
            String qs = "select id, name from Names order by id";
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(qs);
            System.out.println("id" + "\t" + "name");
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                if (rs.wasNull())
                    name = "XXX";
                System.out.println(id + "\t" + name);
            }
            rs.close();
            stmt.close();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
            while (sqle != null) {
                String logMessage = 
                    "\n SQL Error: " + sqle.getMessage() + "\n\t\t" + 
                    "Error code: " + sqle.getErrorCode() + "\n\t\t" + 
                    "SQLState: " + sqle.getSQLState() + "\n";
                System.out.println(logMessage);
                sqle = sqle.getNextException();
            }
        } finally {
            try {
                if (connection != null)
                    connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
