toggle menu

JAVA 정리 - JDBC

2012. 8. 7. 09:18 JAVA

로드 어떤 DB를 사용할지를 선택 | 주로 생성자에서 구현
Class.forName("연결하려는 드라이버명");

Oracle : oracle.jdbc.driver.OracleDriver
MsSQL : sun.jdbc.odbc.JdbcOdbcDriver
MySQL : org.git.mm.mysql.Driver



연결 내가 사용하고자하는 DB에 ID/PW로 접속 | 주로 생성자에서 구현 혹은 필요시마다 연결
Connection connection = DriverManager.getConnection(URL, ID, PW);

Oracle : jdbc:oracle:thin:@localhost:1521:ORCL
MsSQL : jdbc:odbc:odbc설정을통해만든db원본명
MySQL : jdbc:mysql://localhost:3306/db명



실행 CRUD 작업 | 각 SQL 문장마다 메소드를 만드는 것을 권장
//Statement 선언
Statement statement = connection.createStatement();
//int형으로 return값을 받는다. insert, update, delete, create를 수행
statement.executeUpdate(쿼리String);
//결과를 ResultSet으로 받는다.
ResultSet resultSet = statement.executeQuery(쿼리 String); 

Statement 는 일종의 쿼리를 보내기 위해 필요한 권한을 얻는 과정 정도로 생각할 수 있다.

resultSet.next() 는 boolean을 리턴하는데 true면, 다음 레코드가 존재한다는 의미이다.
while( resultSet.next() )
{
	String string = resultSet.getString(1) // 0이 아닌 1부터 시작! 반드시 순차적 접근만 가능!!
	String string = resultSet.getString("name") // 0이 아닌 1부터 시작! 반드시 순차적 접근만 가능!!
}
하나의 Statement 에서는 여러개의 ResultSet을 가질 수 있다.


닫기 반납 | finally 블럭에서 수행하며, 닫기에 해당하는 메소드를 생성하여 사용하는 것이 일반적
resultSet.close();
statement.close();
connection.close();






로드, 연결, 닫기의 기본적인 형태
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExam
{
	Connection connection;
	Statement statement;
	ResultSet resultSet;
	
	String driverName = "oracle.jdbc.driver.OracleDriver";
	String url = "oracle:thin:localhost:1521:ORCL";
	String user = "scott";
	String password = "tiger";
	
	public JDBCExam()
	{
		try
		{
			// ① 로드
			Class.forName(driverName);
			
			// ② 연결
			connection = DriverManager.getConnection(url, user, password);
			
			
		}
		catch (ClassNotFoundException e)
		{
			System.out.println("[로드 오류]\n" + e.getStackTrace());
		}
		catch (SQLException e)
		{
			System.out.println("[연결 오류]\n" +  e.getStackTrace());
		}
		
	}
	
	public void closeDatabase()
	{
		try
		{
			if( connection != null )
			{
				connection.close();
			}
			
			if( statement != null )
			{
				statement.close();
			}
			
			if( resultSet != null )
			{
				resultSet.close();
			}
		}
		catch (SQLException e)
		{
			System.out.println("[닫기 오류]\n" +  e.getStackTrace());
		}
	}
	

	public static void main(String[] args)
	{
		new JDBCExam();
	}
}




간단한 SQL 쿼리를 보내는 예제
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class JDBCExam
{
	Connection connection;
	Statement statement;
	ResultSet resultSet;

	String driverName = "oracle.jdbc.driver.OracleDriver";
	String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
	String user = "scott";
	String password = "tiger";

	public JDBCExam()
	{
		try
		{
			// ① 로드
			Class.forName(driverName);

		}
		catch (ClassNotFoundException e)
		{
			System.out.println("[로드 오류]\n" + e.getStackTrace());
		}

	}

	public void closeDatabase()
	{
		try
		{
			if( connection != null )
			{
				// connection 닫기
				connection.close();
			}

			if( statement != null )
			{
				// statement 닫기
				statement.close();
			}

			if( resultSet != null )
			{
				// resultSet 닫기
				resultSet.close();
			}
		}
		catch (SQLException e)
		{
			System.out.println("[닫기 오류]\n" + e.getStackTrace());
		}
	}

	public int productInsert(int p_no, String p_name, int p_price, String p_detail)
	{
		int resultValue = 0;

		try
		{
			String queryString = "INSERT INTO product VALUES (" + p_no + ", '" + p_name + "', " + p_price + ", '" + p_detail + "')";

			// ② 연결 [Connection]
			connection = DriverManager.getConnection(url, user, password);

			// ② 연결 [Statement]
			statement = connection.createStatement();

			// ③ 실행 [CRUD]
			resultValue = statement.executeUpdate(queryString);
		}
		catch (SQLException e)
		{
			System.out.println("[쿼리 오류]\n" + e.getStackTrace());
		}
		finally
		{
			// ④ 닫기
			closeDatabase();
		}

		return resultValue;

	}

	public void productSelectAll()
	{

		try
		{
			String queryString = "SELECT * FROM product";

			// ② 연결 [Connection]
			connection = DriverManager.getConnection(url, user, password);

			// ② 연결 [Statement]
			statement = connection.createStatement();
			
			// ③ 실행 [CRUD]
			resultSet = statement.executeQuery(queryString);
			
			// 컬럼 정보 가져오기
			ResultSetMetaData resultSetMetaData = resultSet.getMetaData();

			// 컬럼 출력
			System.out.println(resultSetMetaData.getColumnName(1) + "\t" + resultSetMetaData.getColumnName(2) + "\t" + resultSetMetaData.getColumnName(3) + "\t" + resultSetMetaData.getColumnName(4));

			while (resultSet.next())
			{
				System.out.println(resultSet.getInt("p_no") + "\t" + resultSet.getString("p_name") + "\t" + resultSet.getInt("p_price") + "\t" + resultSet.getString("p_detail"));
			}
		}
		catch (SQLException e)
		{
			System.out.println("[쿼리 오류]\n" + e.getStackTrace());
		}
		finally
		{
			// ④ 닫기
			closeDatabase();
		}

	}
	
	public int productRemove(int p_no)
	{
		int resultValue = 0;
		
		try
		{
			String queryString = "DELETE FROM product WHERE p_no=" + p_no;

			// ② 연결 [Connection]
			connection = DriverManager.getConnection(url, user, password);

			// ② 연결 [Statement]
			statement = connection.createStatement();

			// ③ 실행 [CRUD]
			resultValue = statement.executeUpdate(queryString);
		}
		catch (SQLException e)
		{
			System.out.println("[쿼리 오류]\n" + e.getStackTrace());
		}
		finally
		{
			// ④ 닫기
			closeDatabase();
		}
		
		return resultValue;
	}
	
	
	public int productUpdate(int p_no, int p_price, String p_detail)
	{
		int resultValue = 0;

		try
		{
			String queryString = "UPDATE product SET p_price=" + p_price + ", p_detail='" + p_detail + "' WHERE p_no=" + p_no; 

			// ② 연결 [Connection]
			connection = DriverManager.getConnection(url, user, password);

			// ② 연결 [Statement]
			statement = connection.createStatement();

			// ③ 실행 [CRUD]
			resultValue = statement.executeUpdate(queryString);
		}
		catch (SQLException e)
		{
			System.out.println("[쿼리 오류]\n" + e.getStackTrace());
		}
		finally
		{
			// ④ 닫기
			closeDatabase();
		}

		return resultValue;

	}
	
	public void productSelectOne(int p_no)
	{

		try
		{
			String queryString = "SELECT * FROM product WHERE p_no=" + p_no;

			// ② 연결 [Connection]
			connection = DriverManager.getConnection(url, user, password);

			// ② 연결 [Statement]
			statement = connection.createStatement();

			// ③ 실행 [CRUD]
			resultSet = statement.executeQuery(queryString);

			System.out.println("p_no" + "\t" + "p_name" + "\t" + "p_price" + "\t" + "p_detail");

			while (resultSet.next())
			{
				System.out.println(resultSet.getInt("p_no") + "\t" + resultSet.getString("p_name") + "\t" + resultSet.getInt("p_price") + resultSet.getString("p_detail"));
			}
		}
		catch (SQLException e)
		{
			System.out.println("[쿼리 오류]\n" + e.getStackTrace());
		}
		finally
		{
			// ④ 닫기
			closeDatabase();
		}

	}
	
	public void productSearch(String SearchKeyword)
	{

		try
		{
			String queryString = "SELECT * FROM product WHERE p_detail LIKE '%" + SearchKeyword + "%'";

			// ② 연결 [Connection]
			connection = DriverManager.getConnection(url, user, password);

			// ② 연결 [Statement]
			statement = connection.createStatement();

			// ③ 실행 [CRUD]
			resultSet = statement.executeQuery(queryString);

			System.out.println("p_no" + "\t" + "p_name" + "\t" + "p_price" + "\t" + "p_detail");

			while (resultSet.next())
			{
				System.out.println(resultSet.getInt("p_no") + "\t" + resultSet.getString("p_name") + "\t" + resultSet.getInt("p_price") + "\t" + resultSet.getString("p_detail"));
			}
		}
		catch (SQLException e)
		{
			System.out.println("[쿼리 오류]\n" + e.getStackTrace());
		}
		finally
		{
			// ④ 닫기
			closeDatabase();
		}

	}
	

	public static void main(String[] args)
	{
		JDBCExam jdbcExam = new JDBCExam();
		Scanner scanner = new Scanner(System.in);

		System.out.print("번호");
		int p_no = Integer.valueOf(scanner.nextLine());

		System.out.print("이름");
		String p_name = scanner.nextLine();

		System.out.print("가격");
		int p_price = Integer.valueOf(scanner.nextLine());

		System.out.print("내용");
		String p_detail = scanner.nextLine();

		System.out.println("\n\n" + jdbcExam.productInsert(p_no, p_name, p_price, p_detail) + "개의 물품을 추가했습니다.");

		System.out.println("\n\n" + jdbcExam.productRemove(3) + "개의 물품을 삭제했습니다.");
		System.out.println("\n\n" + jdbcExam.productUpdate(4, 5000, "수정완료!!") + "개의 물품을 수정했습니다.");
		
		jdbcExam.productSelectAll();
		jdbcExam.productSelectOne(4);
		jdbcExam.productSearch("비싸");
	}
}




PreparedStatement
//숫자든 문자든 나중에 넣게 될 값들은 ? 로 처리한다.
PreparedStatement preparedStatement = 
connection.prepareStatement("INSERT INTO PRODUCT VALUES (?, ?, ?, ?)");

//물음표 순서대로 값을 설정해준다.
//단! LIKE 연산자를 사용할 수 없다!! ㅠㅠ
preparedStatement.setInt(1, p_no);
preparedStatement.setString(2, p_name);

//실행은 아래와 같이 한다.
preparedStatement.executeUpdate();
preparedStatement.executeQuery();



PreparedStatement를 사용한 예제
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCPre
{
	Connection connection;
	PreparedStatement preparedStatement; 
	ResultSet resultSet;

	public JDBCPre()
	{
		try
		{
			// ① 로드
			Class.forName(DBProperties.DRIVERNAME);

		}
		catch (ClassNotFoundException e)
		{
			System.out.println("[로드 오류]\n" + e.getStackTrace());
		}

	}

	public void closeDatabase()
	{
		try
		{
			if( connection != null )
			{
				// connection 닫기
				connection.close();
			}

			if( preparedStatement != null )
			{
				// statement 닫기
				preparedStatement.close();
			}

			if( resultSet != null )
			{
				// resultSet 닫기
				resultSet.close();
			}
		}
		catch (SQLException e)
		{
			System.out.println("[닫기 오류]\n" + e.getStackTrace());
		}
	}
	
	
	/**
	 * 상품테이블에 insert 하는 메소드 작성
	 */
	public int productInsert(int p_no, String p_name, int p_price, String p_detail)
	{
		int resultValue = 0;

		try
		{
			String queryString = "INSERT INTO product VALUES (?, ?, ?, ?)";

			// ② 연결 [Connection]
			connection = DriverManager.getConnection(DBProperties.URL, DBProperties.USER, DBProperties.PASSWORD);
			
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setInt(1, p_no);
			preparedStatement.setString(2, p_name);
			preparedStatement.setInt(3, p_price);
			preparedStatement.setString(4, p_detail);
			
			// ③ 실행 [CRUD]
			resultValue = preparedStatement.executeUpdate();
		}
		catch (SQLException e)
		{
			System.out.println("[쿼리 오류]\n" + e.getStackTrace());
		}
		finally
		{
			// ④ 닫기
			closeDatabase();
		}

		return resultValue;
	}
	
	public void productSelectAll()
	{

		try
		{
			String queryString = "SELECT * FROM product";

			// ② 연결 [Connection]
			connection = DriverManager.getConnection(DBProperties.URL, DBProperties.USER, DBProperties.PASSWORD);

			// ② 연결 [Statement]
			preparedStatement = connection.prepareStatement(queryString);
			
			// ③ 실행 [CRUD]
			resultSet = preparedStatement.executeQuery();
			
			// 컬럼 정보 가져오기
			ResultSetMetaData resultSetMetaData = resultSet.getMetaData();

			// 컬럼 출력
			System.out.println(resultSetMetaData.getColumnName(1) + "\t" + resultSetMetaData.getColumnName(2) + "\t" + resultSetMetaData.getColumnName(3) + "\t" + resultSetMetaData.getColumnName(4));

			while (resultSet.next())
			{
				System.out.println(resultSet.getInt("p_no") + "\t" + resultSet.getString("p_name") + "\t" + resultSet.getInt("p_price") + "\t" + resultSet.getString("p_detail"));
			}
		}
		catch (SQLException e)
		{
			System.out.println("[쿼리 오류]\n" + e.getStackTrace());
		}
		finally
		{
			// ④ 닫기
			closeDatabase();
		}
	}
	
	
	public int productRemove(int p_no)
	{
		int resultValue = 0;

		try
		{
			String queryString = "DELETE FROM product WHERE p_no=?";

			// ② 연결 [Connection]
			connection = DriverManager.getConnection(DBProperties.URL, DBProperties.USER, DBProperties.PASSWORD);
			
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setInt(1, p_no);
			
			// ③ 실행 [CRUD]
			resultValue = preparedStatement.executeUpdate();
		}
		catch (SQLException e)
		{
			System.out.println("[쿼리 오류]\n" + e.getStackTrace());
		}
		finally
		{
			// ④ 닫기
			closeDatabase();
		}
		
		return resultValue;
	}
	
	
	public int productUpdate(int p_no, int p_price, String p_detail)
	{
		int resultValue = 0;

		try
		{
			String queryString = "UPDATE product SET p_price=?, p_detail=? WHERE p_no=?"; 

			// ② 연결 [Connection]
			connection = DriverManager.getConnection(DBProperties.URL, DBProperties.USER, DBProperties.PASSWORD);
			
			preparedStatement = connection.prepareStatement(queryString);
			preparedStatement.setInt(1, p_price);
			preparedStatement.setString(2, p_detail);
			preparedStatement.setInt(3, p_no);
			
			// ③ 실행 [CRUD]
			resultValue = preparedStatement.executeUpdate();
		}
		catch (SQLException e)
		{
			System.out.println("[쿼리 오류]\n" + e.getStackTrace());
		}
		finally
		{
			// ④ 닫기
			closeDatabase();
		}

		return resultValue;
	}
	

	
	

	public static void main(String[] args)
	{
		JDBCPre JDBCPre = new JDBCPre();
		Scanner scanner = new Scanner(System.in);

		System.out.print("번호");
		int p_no = Integer.valueOf(scanner.nextLine());

		System.out.print("이름");
		String p_name = scanner.nextLine();

		System.out.print("가격");
		int p_price = Integer.valueOf(scanner.nextLine());

		System.out.print("내용");
		String p_detail = scanner.nextLine();

		System.out.println("\n\n" + JDBCPre.productInsert(p_no, p_name, p_price, p_detail) + "개의 물품을 추가했습니다.");

		System.out.println("\n\n" + JDBCPre.productRemove(3) + "개의 물품을 삭제했습니다.");
		System.out.println("\n\n" + JDBCPre.productUpdate(4, 5000, "수정완료!!") + "개의 물품을 수정했습니다.");
		
		JDBCPre.productSelectAll();
	}
}




Connection
A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.
특정 데이터베이스와의 연결 (세션). SQL statement들은 커넥션의 context 안에서 실행되고 결과들이 반환된다.


Statement
The object used for executing a static SQL statement and returning the results it produces.

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

고정된 SQL 문(Statement)을 실행하거나 그것이 만들어낸 결과들을 반환하는데 사용하는 오브젝트.

기본적으로 하나의 Statement 객체당 오직 하나의 ResultSet 객체만이 동시에 열릴 수 있다. 그러므로 만약 하나의 ResultSet 객체가 읽혀지고 있고 그 사이에 다른 ResultSet 객체가 읽혀지는 상황이라면, 반드시 각각 다른 Statement 객체에서 ResultSet 객체가 생성되었어야 할것이다. 





Select 문에 대한 처리의 경우 외부에 보내 출력해야 한다.
일단 ResultSet을 리턴할수는 없다. DB가 닫혀버리고 나면 소용이 없기 때문이다.

레코드를 저장할 수 있는 클래스를 선언해서 저장하는것은 어떨까?
그리고 그 클래스를 넣을 ArrayList를 넣는 것은 어떨까?

그래서 리턴 타입은 흔히 ArrayList<e>의 형태를 갖게 된다.



JAVA 관련 포스팅 더보기