2008년 10월 31일 금요일

java zip 압축관련.


import java.io.*;
import java.util.zip.*;

 

public void creatZipFile() throws Exception {
  

    File f = new File("D:/file/fileup");
  
    String path = "D:/file/fileup";

    String files[] = f.list(); // f object 에 있는 파일목록
    
    // Create a buffer for reading the files
    byte[] buf = new byte[1024];
   
    try {

   

        // Create the ZIP file
        String outFilename = "D:/outfile.zip";
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
   
        // Compress the files
        for (int i=0; i<files.length; i++) {
    
            FileInputStream in = new FileInputStream( path + "/" + files[i]);
   
            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(files[i])); // Zip 파일에 경로를 정하여 저장할수 있다.
    
            // Transfer bytes from the file to the ZIP file
            int len;
            while ((len = in.read(buf)) > 0) {

                out.write(buf, 0, len);
            }
   
            // Complete the entry
            out.closeEntry();
            in.close();
        }
   
        // Complete the ZIP file
        out.close();
    }catch(Exception e) {

        throw e;
    }

}

 

방법2. (BufferedOutputStream, BufferedInputStream 사용)

import java.io.*;
import java.util.zip.*;

 

public void creatZipFile() throws Exception {
  

    File f = new File("D:/file/fileup");

    int size = 1024;
    String path = "D:/file/fileup";

    String files[] = f.list(); // f object 에 있는 파일목록

    // Create a buffer for reading the files
    byte[] buf = new byte[size];
    try {

 

        // Create the ZIP file
        String outFilename = "D:/outfile.zip";
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFilename)));

        // Compress the files
        for (int i=0; i<files.length; i++) {
    
            FileInputStream fs = new FileInputStream( path + "/" + files[i]);

            BufferedInputStream in = new BufferedInputStream(fs, size);


            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(files[i])); // Zip 파일에 경로를 정하여 저장할수 있다.
    
            // Transfer bytes from the file to the ZIP file
            int len;
            while ((len = in.read(buf, 0, size)) > 0) {

                out.write(buf, 0, len);
            }
   
            // Complete the entry
            out.closeEntry();
            in.close();
        }
   
        // Complete the ZIP file
        out.close();
    }catch(Exception e) {

        throw e;
    }

}

java.util.zip 패키지에서 ZIP 압축 화일 형식을 처리하는 클래스의 사용법


다음 프로그램은 압축 화일을 지원하는 java.util.zip 패키지에서
.zip 압축 화일 형식 (다중 화일 압축 형식의 하나)을 처리하는 클래스의
사용법을 보여줍니다.
덧붙여, File 클래스를 사용하여 화일을 다루는 방법, 예외 클래스
중첩된 클래스, java.text 패키지를 이용한 날짜, 메씨지 형식화 출력
방법도 소개합니다.
현재, 이 패키지의 이해를 돕는 문서와 예제가 없어서 간단하게
만들어 보았습니다.


이 프로그램은 zip, unzip, WinZip 프로그램과 같은 일을 하도록
만들어져 있습니다만,
이 프로그램에서 사용된 FileOutputStream이나 FileInputStream을
URL 혹은 Socket 객체로부터 얻은 InputStream 혹은 OutputStream으로
바꾸어주면 네트워크상에서 여러 화일을 하나의 화일로 압축한 형태로
자료를 전송하고 받아서 처리하여, 네트워크 전송 속도를 향상시킬 수
있습니다.
일반 텍스트 자료를 압축하면 2 ~ 4배로 압축된다고 알려져 있습니다.
또한, 이 클래스들은 체크썸을 사용하여 저장, 전송 오류를 검사해줍니다.


이 프로그램이 압축한 화일을 WinZip이 제대로 처리하지 못한다면,
갖고 계신 WinZip 프로그램 버전에 버그가 있기 때문일 것입니다.
http://www.winzip.com 에서 최신 버전 (버전 6.3 Beta 4)을
다운로드받으실 수 있습니다.


- 테스트된 환경: JDK1.1.3 + 솔라리스, JDK1.1.3 + 윈도우즈


----------------- ZipTest.java --------------------------------------
// Usage: java ZipTest [ -r ] zipfile file1 [ file2 ... ]
import java.io.*;
import java.util.zip.*;


class ZipTest
{
static boolean isRecursive = false;
static ZipOutputStream zos;


public static void main( String[] args )
throws IOException
{
try
{ int argnum = 0;
if ( args[argnum].equals("-r") )
{ isRecursive = true;
argnum++;
}
File zipfile = new File( args[argnum++] );
if ( zipfile.exists() )
throw new Error( "ZIP 화일 " + zipfile + "이 이미 존재함." );
zos = new ZipOutputStream( new FileOutputStream( zipfile ) );
if ( args.length <= argnum )
throw new Error(
"사용법: java ZipTest [ -r ] zipfile file1 [ file2 ... ]" );
for(int i = argnum; i < args.length; ++i)
outputEntry( new File(args[i]) );
zos.close();
} catch( Error ex )
{ System.err.println( "오류: " + ex.getMessage() );
}
}

public static void outputEntry( File f ) throws Error, IOException
{ if ( ! f.exists() )
throw new Error( "화일 " + f + "이 존재하지 않음" );
String adjustedPath = f.getPath().replace(File.separatorChar, '/');
if ( f.isDirectory() && ! adjustedPath.endsWith("/") )
adjustedPath += '/';
ZipEntry entry = new ZipEntry( adjustedPath );
entry.setTime( f.lastModified() );
// File 클래스에서 lastModified() 메쏘드의 시각 기준이 문서화되어
// 있지는 않으나, 솔라리스와 윈도우즈에서는 Date 클래스와 같은
// 시각 기준이 사용되고 있음.
zos.putNextEntry( entry );

if ( f.isDirectory() )
{ System.out.println( "디렉토리 첨가: " + f );
if ( isRecursive )
{ String[] files = f.list();
for( int i = 0; i < files.length; ++i )
outputEntry( new File(f, files[i]) ); // 재귀적 호출 사용
}
} else
{ System.out.println( " 화일 첨가: " + f );
FileInputStream fis = new FileInputStream( f );
byte buf[] = new byte[1024];
for( int cnt; (cnt = fis.read(buf)) != -1; )
zos.write( buf, 0, cnt );
fis.close();
}
}


static class Error extends Exception
{ public Error(String mesg)
{ super(mesg); }
}
}
---------------------------------------------------------------------------------



----------------- UnzipTest.java --------------------------------------
// Usage: java UnzipTest [ -l ] zipfile
import java.io.*;
import java.util.zip.*;
import java.util.*;
import java.text.*;


class UnzipTest
{
public static void main( String[] args )
throws IOException
{
try
{
boolean isListing = false;
int argnum = 0;
if ( args[0].equals("-l") )
{ isListing = true;
argnum++;
}
File zipfile = new File( args[argnum] );
if ( ! zipfile.exists() )
throw new Error( "ZIP 화일 " + zipfile + "이 존재하지 않음." );
ZipInputStream zis
= new ZipInputStream( new FileInputStream( zipfile ) );
if ( isListing )
list(zis);
else
extract(zis);
System.out.close();
} catch( Error ex )
{ System.err.println( "오류: " + ex.getMessage() );
}
}


static void list(ZipInputStream zis) throws IOException
{
ZipEntry entry;
System.out.println( " 크기 (압축 크기) 날짜 시각 이름" );
System.out.println( " ---------------- ---- ---- ----" );
MessageFormat fmt = new MessageFormat(
"{0,date,MM-dd-yy} {0,time,HH:mm} {1}" );
while( (entry = zis.getNextEntry()) != null )
{ zis.closeEntry();
System.out.println(
padToWidth( String.valueOf(entry.getSize()), 7 )
+ padToWidth( "(" + String.valueOf(entry.getCompressedSize())
+ ")", 10 )
+ " " + fmt.format( new Object[] {
new Date( entry.getTime() ),
entry.getName() } )
);
}
}


static String padToWidth(String s, int width)
{ if ( s.length() >= width )
return s;
char padded[] = new char[width - s.length()];
for( int i = 0; i < padded.length; i++ )
padded[i] = ' ';
return padded + s;
}


static void extract(ZipInputStream zis) throws IOException, Error
{
ZipEntry entry;
while( (entry = zis.getNextEntry()) != null )
{ File entryFile
= new File( entry.getName().replace('/', File.separatorChar) );
if ( entry.isDirectory() )
{ if ( ! entryFile.exists() )
{ System.out.println( " 디렉토리 생성: " + entryFile );
entryFile.mkdirs();
}
continue;
}


if ( entryFile.getParent() != null )
{ File parent = new File( entryFile.getParent() );
if ( ! parent.exists() )
parent.mkdirs();
}
if ( entry.getMethod() == ZipEntry.STORED )
{ System.out.println( " 추출: " + entryFile );
} else if ( entry.getMethod() == ZipEntry.DEFLATED )
{ System.out.println( " 압축 풀기: " + entryFile );
} else
throw new Error( entryFile
+ "화일에서 처리할 수 없는 압축 방식이 사용되었음" );
if ( entryFile.exists() )
throw new Error( entryFile + "이 이미 존재함" );
FileOutputStream fos = new FileOutputStream( entryFile );
byte buf[] = new byte[1024];
for( int cnt; (cnt = zis.read(buf)) != -1; )
fos.write( buf, 0, cnt );
fos.close();
}
}


static class Error extends Exception
{ public Error(String mesg)
{ super(mesg); }
}
}
---------------------------------------------------------------------------------



----------- 실행 결과 ------------------------
C:\example\zip> mkdir test
C:\example\zip> copy *.java test
C:\example\zip> dir test
GZIPT~66 JAV 2,333 97-07-24 3:48 GZIPTest.java
UNZIP~U2 JAV 3,637 97-07-24 3:53 UnzipTest.java
ZIPTE~7G JAV 2,479 97-07-24 3:27 ZipTest.java
CHECK~Z6 JAV 1,674 97-07-22 6:11 CheckedStreamTest.java
C:\example\zip> java -Duser.timezone=JST ZipTest -r test.zip test
-------------------> workaround for JDK1.1 timezone bug
디렉토리 첨가: test
화일 첨가: test\GZIPTest.java
화일 첨가: test\CheckedStreamTest.java
화일 첨가: test\ZipTest.java
화일 첨가: test\UnzipTest.java
C:\example\zip> java -Duser.timezone=JST UnzipTest -l test.zip
크기 (압축 크기) 날짜 시각 이름
---------------- ---- ---- ----
0 (2) 07-25-97 01:15 test/
2333 (785) 07-24-97 03:48 test/GZIPTest.java
3637 (1243) 07-24-97 03:53 test/UnzipTest.java
2479 (1027) 07-24-97 03:27 test/ZipTest.java
1674 (586) 07-22-97 06:11 test/CheckedStreamTest.java
C:\example\zip> move test test2
C:\example\zip> java UnzipTest test.zip
디렉토리 생성: test\
압축 풀기: test\GZIPTest.java
압축 풀기: test\UnzipTest.java
압축 풀기: test\ZipTest.java
압축 풀기: test\CheckedStreamTest.java


(WinZip 프로그램과의 호환성 테스트)
C:\example\zip> move test test3
(WinZip에서 test.zip을 Extract한다)
C:\example\zip> dir test
GZIPT~66 JAV 2,333 97-07-24 3:48 GZIPTest.java
UNZIP~U2 JAV 3,637 97-07-24 3:53 UnzipTest.java
ZIPTE~7G JAV 2,479 97-07-24 3:27 ZipTest.java
CHECK~Z6 JAV 1,674 97-07-22 6:11 CheckedStreamTest.java
C:\example\zip> move test test4


(WinZip에서 test2.zip을 생성후, test2\*.*를 첨가)
C:\example\zip> java -Duser.timezone=JST UnzipTest -l test2.zip
크기 (압축 크기) 날짜 시각 이름
---------------- ---- ---- ----
2333 (785) 07-24-97 03:48 GZIPTest.java
3637 (1253) 07-24-97 03:53 UnzipTest.java
2479 (1031) 07-24-97 03:27 ZipTest.java
1674 (586) 07-22-97 06:11 CheckedStreamTest.java
C:\example\zip> mkdir test
C:\example\zip> cd test
C:\example\zip\test> set CLASSPATH=..
C:\example\zip\test> java UnzipTest ..\test2.zip
압축 풀기: GZIPTest.java
압축 풀기: UnzipTest.java
압축 풀기: ZipTest.java
압축 풀기: CheckedStreamTest.java
C:\example\zip\test> dir *.*
GZIPT~66 JAV 2,333 97-07-25 1:28 GZIPTest.java
UNZIP~U2 JAV 3,637 97-07-25 1:28 UnzipTest.java
ZIPTE~7G JAV 2,479 97-07-25 1:28 ZipTest.java
CHECK~Z6 JAV 1,674 97-07-25 1:28 CheckedStreamTest.java

2008년 10월 30일 목요일

Creating ZIP and JAR Files(JAVA)

Creating ZIP and JAR Files

ZIP files offer a packaging mechanism, allowing multiple files to be bundled together as one. Thus, when you need to download a group of files from the web, you can package them into one ZIP file for easier transport as a single file. The bundling can include additional information like directory hierarchy, thus preserving necessary paths for an application or series of resources once unbundled.

This tip will address three aspects of ZIP file usage:

  • creating them
  • adding files to them
  • compressing those added files

Creating Zip Streams

The ZipOutputStream offers a stream for compressing the outgoing bytes. There is a single constructor for ZipOutputStream, one that accepts another OutputStream:

public ZipOutputStream(OutputStream out)

If the constructor argument is the type FileOutputStream, then the compressed bytes written by the ZipOutputStream will be saved to a file. However, you aren't limited to using the ZipOutputStream with a file. You can also use the OutputStream that comes from a socket connection or some other non-file-oriented stream. Thus, for a file-oriented ZipOutputStream, the typical usage will look like this:

String path = "afile.zip"; 
FileOutputStream fos = new FileOutputStream(path);
ZipOutputStream zos = new ZipOutputStream(fos);

Adding Entries

Once created, you don't just write bytes to a ZipOutputStream. Instead, you need to treat the output stream as a collection of components. Each component of a ZipOutputStream is paired with a ZipEntry. It is this ZipEntry that you create and then add to the ZipOutputStream before actually writing its contents to the stream.

String name = ...; 
ZipEntry entry = new ZipEntry(name);
zos.putNextEntry(entry);
zos.write(<< all the bytes for entry >>);

Each entry serves as a marker in the overall stream, where you'll find the bytes related to the entry in the library file. After the ZIP file has been created, when you need to get the entry contents back, just ask for the related input stream:

ZipFile zip = new ZipFile("afile.zip"); 
ZipEntry entry = zip.getEntry("anEntry.name");
InputStream is = zip.getInputStream(entry);

Now that you've seen how to create the zip file and add entries to that file, it is important to point out that the java.util.zip libraries offer some level of control for the added entries of the ZipOutputStream. First, the order you add entries to the ZipOutputStream is the order they are physically located in the .zip file. You can manipulate the enumeration of entries returned back by the entries() method of ZipFile to produce a list in alphabetical or size order, but the entries are still stored in the order they were written to the output stream.

Compressing Files

Files added to a ZIP/JAR file are compressed individually. Unlike Microsoft CAB files which compress the library package as a whole, files in a ZIP/JAR file are each compressed or not compressed separately. Before adding a ZipEntry to the ZipOutputStream, you determine whether its associated bytes are compressed. The setMethod method of ZipEntry allows you to specify which of the two available compression formats to use. Use the STORED constant of ZipEntry to give you an uncompressed file and the DEFLATED setting for a compressed version. You cannot control the compression efficiency. That depends on the type of data in the associated entry. Straight text can be compressed to around 80% of its size quite easily, whereas MP3 or JPEG data will be compressed much less.

While you might think it obvious that everything should be compressed, it does take time to compress and uncompress a file. If the task of compressing is too costly a task to do at the point of creation, it may sometimes be better to just store the data of the whole file in a STORED format, which just stores the raw bytes. The same can be said of the time cost of uncompression. Of course, uncompressed files are larger, and you have to pay the cost with either higher disk space usage or bandwidth when transferring file. Keep in mind that you need to change the setting for each entry, not the ZipFile as a whole. However, it is more typical to compress or not compress a whole ZipFile, as opposed to different settings for each entry.

There is one key thing you need to know if you use the STORED constant for the compression method: you must explicitly set certain attributes of the ZipEntry which are automatically set when the entry is compressed. These are the size, compressed size, and the checksum of the entry's input stream. Assuming an input file, the size and compressed size can just be the file size. To compute the checksum, use the CRC32 class in the java.util.zip package. You cannot just pass in 0 or -1 to ignore the checksum value; the CRC value will be used to validate your input when creating the ZIP and when reading from it later.

ZipEntry entry = new ZipEntry(name);
entry.setMethod(ZipEntry.STORED);
entry.setCompressedSize(file.length());
entry.setSize(file.length());
CRC32 crc = new CRC32();
crc.update(<< all the bytes for entry >>);
entry.setCrc(crc.getValue());
zos.putNextEntry(entry);

To demonstrate, the following program will combine a series of files using the STORED compression method. The first argument to the program will be the ZIP file to create. Remaining arguments represent the files to add. If the ZIP file to create already exists, the program will exit without modifying the file. If you add a non-existing file to the ZIP file, the program will skip the non-existing file, adding any remaining command line arguments to the created ZIP.

import java.util.zip.*;
import java.io.*;

public class ZipIt {
public static void main(String args[]) throws IOException {
if (args.length < 2) {
System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");
System.exit(-1);
}
File zipFile = new File(args[0]);
if (zipFile.exists()) {
System.err.println("Zip file already exists, please try another");
System.exit(-2);
}
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
int bytesRead;
byte[] buffer = new byte[1024];
CRC32 crc = new CRC32();
for (int i=1, n=args.length; i < n; i++) {
String name = args[i];
File file = new File(name);
if (!file.exists()) {
System.err.println("Skipping: " + name);
continue;
}
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
crc.reset();
while ((bytesRead = bis.read(buffer)) != -1) {
crc.update(buffer, 0, bytesRead);
}
bis.close();
// Reset to beginning of input stream
bis = new BufferedInputStream(
new FileInputStream(file));
ZipEntry entry = new ZipEntry(name);
entry.setMethod(ZipEntry.STORED);
entry.setCompressedSize(file.length());
entry.setSize(file.length());
entry.setCrc(crc.getValue());
zos.putNextEntry(entry);
while ((bytesRead = bis.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
}
bis.close();
}
zos.close();
}
}

More Information

For more information on JAR files, including how to seal and version them, be sure to visit the "Packing Programs in JAR Files" lesson in The Java Tutorial

2008년 10월 21일 화요일

Oracle Sequence 와 Trigger 생성

Sequence 생성
create sequence autonum6 increment by 1 start with 1 nomaxvalue nocycle nocache;

Triger  생성
create trigger auto_trigger6
before insert on Reservation
for each row
begin
select autonum6.nextval into :new.id from dual;
end;
/

시퀀스를 만들고 트리거를 실행하면 자동으로 증가한다.

auto_increment를 사용해도 된다.
예를들어  시퀀스만을 만들고(트리거는 안씀)
insert into test (num)  values (autonum.nextval); 도 가능하다.

CYON Cinema Friday 이벤트(26회 바디 오브 라이즈) 당첨

안녕하세요. 싸이언 운영자입니다.

CYON Cinema Friday 이벤트 당첨을 진심으로 축하드립니다.

CYON Cinema Friday '26th Choice 바디 오브 라이즈'에 응모해주신 모든 분들께 감사드리며,
앞으로 계속되는 Cinema Friday에 많은참여 바랍니다.

* 21~23일, 당첨자 확인전화 연결이 안되신 분은 자동으로 당첨취소가 되므로 연락을 못받으신분은 23일까지 연락주시기 바랍니다. (Tel.080-639-5555)


감사합니다.

<바디 오브 라이즈 영화상영 안내>

* 일시 : 10월 24일 금요일 8시
* 장소 : 서울 코엑스 메가박스
* 경품내역 : 바디 오브 라이즈 영화 관람권 (1인2매)
* 티켓 수령처 : 코엑스 메가박스 CYON PLANET(영화매표소 커피빈 옆)
* 티켓 수령방법 : 영화 상영일부터 30분전까지 티켓수령 가능(신분증 확인 후 수령, 신분증 필지참)


2008년 10월 1일 수요일

Transaction Control Language (TCL)

Transaction Control Language (TCL)

Transaction control statements manage changes made by DML statements.

What is a Transaction?

A transaction is a set of SQL statements which Oracle treats as a Single Unit. i.e. all the statements should execute successfully or none of the statements should execute.

To control transactions Oracle does not made permanent any DML statements unless you commit it. If you don’t commit the transaction and power goes off or system crashes then the transaction is roll backed.

TCL Statements available in Oracle are

COMMIT       :Make changes done in  transaction permanent.

ROLLBACK  :Rollbacks the state of database to the last commit point.

SAVEPOINT :Use to specify a point in transaction to which later you can rollback.

COMMIT

To make the changes done in a transaction permanent issue the COMMIT statement.

The syntax of COMMIT Statement is

COMMIT  [WORK]  [COMMENT ‘your comment’];

WORK is optional.

COMMENT is also optional, specify this if you want to identify this transaction in data dictionary DBA_2PC_PENDING.

Example

insert into emp (empno,ename,sal) values (101,’Abid’,2300);

commit;

 

ROLLBACK

 

To rollback the changes done in a transaction give rollback statement. Rollback restore the state of the database to the last commit point.

 

 

Example :

delete from emp;

rollback;          /* undo the changes */

 

 

SAVEPOINT

 

Specify a point in a transaction to which later you can roll back.

 

Example

 

insert into emp (empno,ename,sal) values (109,’Sami’,3000);

savepoint a;

insert into dept values (10,’Sales’,’Hyd’);

savepoint b;

insert into salgrade values (‘III’,9000,12000);

 

Now if you give

 

rollback to a;

 

Then  row from salgrade table and dept will be roll backed. Now you can commit the row inserted into emp table or rollback the transaction.

 

If you give

 

rollback to b;

 

Then row inserted into salgrade table will be roll backed. Now you can commit the row inserted into dept table and emp table or rollback to savepoint a or completely roll backed the transaction.

 

If you give

 

rollback;

 

Then the whole transactions is roll backed.

 

If you give

 

commit;

 

Then the whole transaction is committed and all savepoints are removed.


Oracle Isolation Level

Transaction Isolation Level(격리수준)을 이해하기
 
이번 기사에서는 지난 Deadlock 발생을 감소시키는 방법 기사에서 언급되었던 한 세션 상의 모든 SELECT 문장에 대한 디폴트 트랜잭션 잠금 동작을 제어하는 Transaction Isolation Level에 대하여 알아보자.
 
트랜잭션에서 일관성이 없는 데이터를 허용하도록 하는 수준을 Isolation Level(격리수준)이라고 한다. 예를 들어, 한 사용자가 어떠한 데이터를 수정하고 있는 경우 다른 사용자들이 그 데이터에 접근하는 것을 차단함으로써 완전한 데이터만을 사용자들에게 제공하게 된다. 또한, 많은 사용자들의 수정 작업으로 인하여 통계 자료를 작성할 수 없는 사용자를 위하여 읽기 작업을 수행할 수 있도록 Isolation Level을 변경할 수 있다.
 
ANSI에서 작성된 SQL-92 표준은 네 종류의 Isolation Level을 정의하고 있으며 SQL Server 7.0, 2000은 이 표준을 준수한다. Isolation Level을 조정하는 경우 동시성이 증가되는데 반해 데이터의 무결성에 문제가 발생할 수 있거나, 데이터의 무결성을 완벽하게 유지하는 데 반하여 동시성이 떨어질 수 있으므로 그 기능을 완벽하게 이해한 후에 사용해야 한다.
 
현재 설정된 Isolation Level을 보고자 하는 경우 DBCC USEROPTIONS 를 이용한다.
 
다음은 SQL Server에서 지원하는 네 종류의 Transaction Isolation Level이다.
l        Read Uncommitted
l        Read Committed
l        Repeatable Read
l        Serializable
 
Read Uncommitted Isolation Level
SELECT 문장을 수행하는 경우 해당 데이터에 Shared Lock이 걸리지 않는 Level이다. 따라서, 어떤 사용자가 A라는 데이터를 B라는 데이터로 변경하는 동안 다른 사용자는 B라는 아직 완료되지 않은(Uncommitted 혹은 Dirty) 데이터 B를 읽을 수 있다.
 
Read Committed Isolation Level
SQL Server Default로 사용하는 Isolation Level이다. Level에선 SELECT 문장이 수행되는 동안 해당 데이터에 Shared Lock이 걸린다. 그러므로, 어떠한 사용자가 A라는 데이터를 B라는 데이터로 변경하는 동안 다른 사용자는 해당 데이터에 접근할 수 없다.
 
Repeatable Read Isolation Level
트랜잭션이 완료될 때까지 SELECT 문장이 사용하는 모든 데이터에 Shared Lock이 걸리므로 다른 사용자는 그 영역에 해당되는 데이터에 대한 수정이 불가능하다. 가령, Select col1 from A where col1 between 1 and 10을 수행하였고 이 범위에 해당하는 데이터가 2건이 있는 경우(col1=1 5) 다른 사용자가 col1 1이나 5 Row에 대한 UPDATE가 불가능하다. 하지만, col1 1 5를 제외한 나머지 이 범위에 해당하는 Row INSERT하는 것이 가능하다.
 
Serializable Isolation Level
트랜잭션이 완료될 때까지 SELECT 문장이 사용하는 모든 데이터에 Shared Lock이 걸리므로 다른 사용자는 그 영역에 해당되는 데이터에 대한 수정 및 입력이 불가능하다. 예를 들어, Repeatable Read의 경우 1에서 10 사이에 해당되는 데이터에 대한 UPADTE가 가능하였다. 하지만 이 Level에서는 UPDATE 작업도 허용하지 않는다.
 
사용 방법
SET TRANSACTION ISOLATION LEVEL
{
READ COMMITTED
| READ UNCOMMITTED
| REPEATABLE READ
| SERIALIZABLE
}
, SET 문장을 이용하여 Transaction Isolation Level을 정의하게 되므로 해당 Session에서만 Isolation Level이 적용된다.
 
사용 예제
다음 예제는 세션에 대해 TRANSACTION ISOLATION LEVEL을 설정한다. 뒤따르는 각 Transact-SQL 문에 대해 SQL Server는 트랜잭션이 끝날 때까지 모든 공유 잠금을 유지한다.
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ
GO
BEGIN TRANSACTION
SELECT * FROM publishers
SELECT * FROM authors
...
COMMIT TRANSACTION