/*
drop table test;

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

select * from Names;
*/

import java.sql.*;

public class Wsady {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws ClassNotFoundException
	{
		Connection connection=null;
		int[] ile;
		String[] imiona = { "Ala", "Basia", "Dusia", "Gienia", "Kasia" };
		try
		{
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=KursBD;user=sa;password=sql2005");
			Statement stmt = connection.createStatement();
			stmt.addBatch( "delete from names" );
			for ( int i=0; i<imiona.length; i++ )
			{
				stmt.addBatch( "insert into names values("+(i+1)+", '"+imiona[i]+"')" );
			}
			stmt.addBatch( "update names set name='XXX' where id<=4" );
			//stmt.addBatch( "insert into names values( 1, 'Zosia' )" ); // drugi raz odkomentowujemy ten wiersz
			stmt.addBatch( "delete from names" );
			//stmt.clearBatch();
			ile = stmt.executeBatch();
			for ( int i=0; i<ile.length; i++ )
			{
				System.out.println( "Ilość przetworzonych wierszy w instrukcji "+(i+1)+": "+ile[i] );				
			}
			stmt.close();
		}
		catch ( BatchUpdateException e )
		{
			int[] count=e.getUpdateCounts();
			for ( int i=0; i<count.length; i++ )
			{
				System.out.println( "Błąd: ilość przetworzonych wierszy w instrukcji "+(i+1)+": "+count[i] );				
			}			
		}
		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(); }
		}
	}

}
