// Programm 6-23e: BSP_ROOT/meinewebapp/WEB-INF/classes/meinetags/SqlDirektAbfrageTag.java
package meinetags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.sql.*;
public class SqlDirektAbfrageTag extends BodyTagSupport {
  String ident, treiber, jdbcurl, uid, passwd;
  JspWriter out;
  Statement s;
  public void setIdent(String ident) { this.ident = ident; }
  public void setTreiber(String treiber) { this.treiber = treiber; }
  public void setJdbcurl(String jdbcurl) { this.jdbcurl = jdbcurl; }
  public void setUid(String uid) { this.uid = uid; }
  public void setPasswd(String passwd) { this.passwd = passwd; }
  public int doStartTag() throws JspException {
    try {
      out = pageContext.getOut();
      Class.forName(treiber);
      Connection c = DriverManager.getConnection(jdbcurl, uid, passwd);
      s = c.createStatement();
    }
    catch (Exception ex) { throw new JspTagException("Fehler " + ex); }
    return EVAL_BODY_BUFFERED;
  }
  public int doAfterBody() throws JspException {
    String sql = getBodyContent().getString();
    getBodyContent().clearBody();
    try {
      ResultSet r = s.executeQuery(sql);
      ResultSetMetaData rm = r.getMetaData();
      for (int i = 1; i <= rm.getColumnCount(); i++) 
        out.println(rm.getColumnName(i) + (i==rm.getColumnCount() ? "<BR>" : ";"));
      pageContext.setAttribute(ident, r);
   }
    catch (Exception ex) { throw new JspTagException("Fehler " + ex); }
    return SKIP_BODY;
  }
  public int doEndTag() throws JspException {
    return EVAL_PAGE;
  }
}