import java.io.*;
import java.sql.*;
import java.util.Date;

public class InsertItem
{
	public InsertItem()
	{
	}

	public void loadDriver() throws ClassNotFoundException, Exception
	{
  		Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
	}


	public void insert(BoardData data, String remoteAddr) throws SQLException
	{
       		String url="jdbc:oracle:thin:@localhost:1521:etri";
        		Connection con;
       		Statement stmt;

      		String name = data.name;
      		String email = data.email;
      		String title = data.title;
       		String content = data.content;
        		String password = data.password;
        		// getParameter메소드를 이용해 input.html로 부터 전달된 데이터를 얻습니다.
        		// 전달된 데이터드을 할글처리를 위해 ByteToKSC5601을 이용해 변환합니다.

   		// DB Connect
   		con = DriverManager.getConnection(url, "scott", "tiger");
   		stmt = con.createStatement();

   		String CountQuery = "select max(BNUM) as rc from board ";
   		ResultSet rc = stmt.executeQuery(CountQuery);
   		rc.next();

   		int num  = rc.getInt("rc") + 1;

   		System.out.println("num = " + num);
   		String query = "insert into board(BNUM, BDATE, BNAME, BEMAIL, BTITLE, BCONTENT, BPASSWORD) values(" +
	                        num + ", SYSDATE, '" + toHangul(name) + "', '" + toHangul(email) + "', '" +
	                        toHangul(title) + "', '" + toHangul(content) + "', '" + password + "', '" +  remoteAddr + "' )";
     			//  getRemoteAddr을 사용하여 글 작성자의  IP를 확인합니다.

   		ResultSet rs = stmt.executeQuery(query);

   		stmt.close();
   		con.close();
   	}

   	// 데이타베이스에 쓸때
   	private String toHangul(String str)
   	{
      		if (str == null)
             		return null;
      		try
      		{
         		return new String(str.getBytes("8859_1"), "KSC5601");
      		}
      		catch (UnsupportedEncodingException e)
      		{
      		}
      		return null;
   	}

	//한글을 데이터베이스의 유니코드로 변환
   	private String hangulTo(String str)
   	{
      		if (str == null)
            		return null;
      		try
      		{
            		return new String(str.getBytes("KSC5601"), "8859_1");
      		}
      		catch (UnsupportedEncodingException e)
      		{
      		}
      		return null;
   	}
}
