Основы проектирования приложений баз данных



         

Вызов методов компонентов JAVABEANS из JSP-файла - часть 5


protected void go() // Подключение к БД и выполнение запроса throws ClassNotFoundException, SQLException { // Загрузка JDBC-драйвера Class.forName(classname); // Создание соединения с базой данных Connection con = DriverManager.getConnection(url, username, password); // Создание и выполнение запроса Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); ResultSetMetaData rsmd = rs.getMetaData(); cols = rsmd.getColumnCount(); rows = 0; result = new Vector(); String s[] = new String[cols]; for (int i=1; i<=cols; i++) { s[i-1] = rsmd.getColumnLabel(i) ; } result.addElement(s); rows ++; // Извлечение данных while (rs.next()) { s = new String[cols]; for (int i=1; i<=cols; i++) { s[i-1] = helper(rs, rsmd.getColumnType(i), i); } result.addElement(s); rows ++; } } public static void main (String[] args) { JDBCBean jdbcBean = new JDBCBean(); String classname = "com.imaginary.sql.msql.MsqlDriver"; //String url = "jdbc:msql://gaby.eng:4333/demo"; String url = "jdbc:msql://ridgetop.eng:1114/test"; String username = "lfu"; String password = "password"; //String query = "select * from details"; String query = "select * from table1"; jdbcBean.setClassname(classname); jdbcBean.setUrl(url); jdbcBean.setUsername(username); jdbcBean.setPassword(password); jdbcBean.setQuery(query); try { jdbcBean.go(); System.out.println("Seems okay"); } catch (Exception ex) { ex.printStackTrace(); } } public int getColumnCount() { return cols; } public int getRowCount() { return rows; } public String getColumnLabels(int col) { String[] s = (String[])result.firstElement(); return s[col]; } public String getCell(int col, int row) { String[] s = (String[])result.elementAt(row); return s[col]; } protected String helper (ResultSet rs, int dataType, int col) throws SQLException { String retVal = null; Integer intObj; // Запрос данных в зависимости от их типа switch(dataType) { case Types.DATE: java.sql.Date date = rs.getDate(col); retVal = date.toString(); break; case Types.TIME: java.sql.Time time = rs.getTime(col); retVal = time.toString(); break; case Types.TIMESTAMP: java.sql.Timestamp timestamp = rs.getTimestamp(col); retVal = timestamp.toString(); break; case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: retVal = rs.getString(col); break; case Types.NUMERIC: case Types.DECIMAL: java.math.BigDecimal numeric = rs.getBigDecimal(col, 10); retVal = numeric.toString(); break; case Types.BIT: boolean bit = rs.getBoolean(col); Boolean boolObj = new Boolean(bit); retVal = boolObj.toString(); break; case Types.TINYINT: byte tinyint = rs.getByte(col); intObj = new Integer(tinyint); retVal = intObj.toString(); break; case Types.SMALLINT: short smallint = rs.getShort(col); intObj = new Integer(smallint); retVal = intObj.toString(); break; case Types.INTEGER: int integer = rs.getInt(col); intObj = new Integer(integer); retVal = intObj.toString(); break; case Types.BIGINT: long bigint = rs.getLong(col); Long longObj = new Long(bigint); retVal = longObj.toString(); break; case Types.REAL: float real = rs.getFloat(col); Float floatObj = new Float(real); retVal = floatObj.toString(); break; case Types.FLOAT: case Types.DOUBLE: double longreal = rs.getDouble(col); Double doubleObj = new Double(longreal); retVal = doubleObj.toString(); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: byte[] binary = rs.getBytes(col); retVal = new String(binary); break; } return retVal; } } // Код файла HttpJDBCBean.java: package myjspjdbc1; import java.io.*; import java.util.*; import javax.servlet.http.*; import java.sql.*; public class HttpJDBCBean extends JDBCBean { public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { // Получение значений параметров, если они заданы String _p ; if ((_p = request.getParameter("classname")) != null) { classname = _p; } if ((_p = request.getParameter("url")) != null) { url = _p; } if ((_p = request.getParameter("username")) != null) { username = _p; } if ((_p = request.getParameter("password")) != null) { password = _p; } if ((_p = request.getParameter("query")) != null) { query = _p; } // Если параметры не заданы, то отображать только форму boolean form_only = false; if (classname == "" || classname == null) form_only = true; if (url == "" || url == null) form_only = true; if (username == null) form_only = true; if (password == null) form_only = true; if (query == null) form_only = true; if (form_only) { return; } try { this.go(); // Вызов метода, выполняющего запрос } catch (ClassNotFoundException ex) { PrintWriter writer = response.getWriter(); // Поток вывода writer.println("class " + classname + " not found."); } catch (SQLException ex) { PrintWriter writer = response.getWriter(); writer.println("Message: " + ex.getMessage()); writer.println("Error code: " + ex.getErrorCode()); ex.printStackTrace(writer); } catch (Exception ex) { PrintWriter writer = response.getWriter(); ex.printStackTrace(writer); } } }




Содержание  Назад  Вперед