public void eliminarConfiguracion(int usuario) throws DAOException { log.info("eliminarConfiguracion(int usuario)"); Connection cons = null; PreparedStatement stmt = null; try { String query = "DELETE FROM cv_servicio_usuario WHERE IDUSUARIO=?"; cons = dataSource.getConnection(); stmt = cons.prepareStatement(query); stmt.setInt(1, usuario); stmt.executeUpdate(); query = "insert into cv_servicio_usuario(idusuario,idservicio,columna,posicion,visible,estado) " + "select ?,idservicio,columna,posicion,usuario_visible,usuario_estado " + "from cv_servicio_maestro"; stmt = cons.prepareStatement(query); stmt.setInt(1, usuario); stmt.executeUpdate(); } catch (SQLException e) { log.info(e.toString()); throw new DAOException(e.toString()); } catch (Exception e) { log.info(e.toString()); throw new DAOException(e.toString()); } finally { closeStatement(stmt); closeConnection(cons); } }
private String createTableFiles() throws SQLException { String r = "Table Files created!"; try { // creates a SQL Statement object in order to execute the SQL insert command stmt = conn.createStatement(); stmt.execute( "CREATE TABLE Files (" + "FileID int NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1 ) PRIMARY KEY, " + "Filename varchar(100) NOT NULL, " + "Size int NOT NULL, " + "DateUpload DATE NOT NULL, " + "TimeUpload TIME NOT NULL, " + "Sender int NOT NULL, " + "Receiver int NOT NULL, " + "IsDelivered boolean DEFAULT false NOT NULL, " + "FOREIGN KEY (Sender) REFERENCES Profiles(ProfileID), " + "FOREIGN KEY (Receiver) REFERENCES Profiles(ProfileID))"); stmt.close(); } catch (SQLException e) { System.err.println(e.toString()); if (!e.getSQLState().equalsIgnoreCase("X0Y32")) { return r; } r = e.toString(); throw e; } return r; }
public static String[][] getSqlInjectionResult(String ApplicationRoot, String username) { Encoder encoder = ESAPI.encoder(); String[][] result = new String[10][3]; try { Connection conn = Database.getSqlInjLessonConnection(ApplicationRoot); Statement stmt; stmt = conn.createStatement(); ResultSet resultSet = stmt.executeQuery("SELECT * FROM tb_users WHERE username = '******'"); log.debug("Opening Result Set from query"); for (int i = 0; resultSet.next(); i++) { log.debug("Row " + i + ": User ID = " + resultSet.getString(1)); result[i][0] = encoder.encodeForHTML(resultSet.getString(1)); result[i][1] = encoder.encodeForHTML(resultSet.getString(2)); result[i][2] = encoder.encodeForHTML(resultSet.getString(3)); } log.debug("That's All"); } catch (SQLException e) { log.debug("SQL Error caught - " + e.toString()); result[0][0] = "error"; result[0][1] = encoder.encodeForHTML(e.toString()); } catch (Exception e) { log.fatal("Error: " + e.toString()); } return result; }
/** * _more_ * * @return _more_ */ public Connection getConnection() { if (connection != null) { return connection; } String url = getFilename(); if ((dataSource.getUserName() == null) || (dataSource.getUserName().trim().length() == 0)) { if (url.indexOf("?") >= 0) { int idx = url.indexOf("?"); List<String> args = (List<String>) StringUtil.split(url.substring(idx + 1), "&", true, true); url = url.substring(0, idx); for (String tok : args) { List<String> subtoks = (List<String>) StringUtil.split(tok, "=", true, true); if (subtoks.size() != 2) { continue; } String name = subtoks.get(0); String value = subtoks.get(1); if (name.equals("user")) { dataSource.setUserName(value); } else if (name.equals("password")) { dataSource.setPassword(value); } } } } int cnt = 0; while (true) { String userName = dataSource.getUserName(); String password = dataSource.getPassword(); if (userName == null) { userName = ""; } if (password == null) { password = ""; } try { connection = DriverManager.getConnection(url, userName, password); return connection; } catch (SQLException sqe) { if ((sqe.toString().indexOf("role \"" + userName + "\" does not exist") >= 0) || (sqe.toString().indexOf("user name specified") >= 0)) { String label; if (cnt == 0) { label = "<html>The database requires a login.<br>Please enter a user name and password:</html>"; } else { label = "<html>Incorrect username/password. Please try again.</html>"; } if (!dataSource.showPasswordDialog("Database Login", label)) { return null; } cnt++; continue; } throw new BadDataException("Unable to connect to database", sqe); } } }
private void producto() { DefaultTableModel modelo = new DefaultTableModel(); try { Statement estatuto = conex.getCn().createStatement(); ResultSet resultado = estatuto.executeQuery( "SELECT idProducto Codigo, Producto, Precio, IF(Servicio = true, 'Servicio', Cantidad) Cantidad FROM producto order by Producto asc"); String[] Titulos = {"Codigo", "Nombre", "Precio", "Cantidad"}; modelo.setColumnIdentifiers(Titulos); while (resultado.next()) { Object[] fila = { resultado.getObject("Codigo"), resultado.getObject("Producto"), resultado.getObject("Precio"), resultado.getObject("Cantidad") }; modelo.addRow(fila); } TableProducto.setModel(modelo); } catch (SQLException e) { setTitle(e.toString()); JOptionPane.showMessageDialog( null, e.toString(), "Student Control", JOptionPane.INFORMATION_MESSAGE); } }
@After public void tearDown() { try { manager.close(); } catch (SQLException sqlE) { LOG.error("Got SQLException: " + sqlE.toString()); fail("Got SQLException: " + sqlE.toString()); } }
public void showTables() { if (this.tab_PosList.getSelectedRow() == 0) { this.btn_PosDel.setEnabled(false); this.btn_PosUpdate.setEnabled(false); this.btn_StaffPosUpdata.setEnabled(true); } else { this.btn_PosDel.setEnabled(true); this.btn_PosUpdate.setEnabled(true); this.btn_StaffPosUpdata.setEnabled(true); } // String tabSelect = tab_PosList.getValueAt(this.tab_PosList.getSelectedRow(), // 0).toString(); String sql = ""; ResultSet rs_Pos = null; try { if (tab_PosList.getSelectedRow() == 0) { sql = " SELECT staff_info.s_no AS NO, " + "concat(staff_info.firstname, staff_info.lastName) AS Name, " + "staff_info.nia_no AS ID_NO, " + "staff_info.s_id AS Account " + " FROM staff_info " + " WHERE staff_info.posi_guid IS null" + " AND staff_info.exist = 1"; } else if (tab_PosList.getSelectedRow() != 0 && tab_PosList.getSelectedRow() != -1) { sql = " SELECT staff_info.s_no AS NO, " + "concat(staff_info.firstname, staff_info.lastName) AS Name, " + "staff_info.nia_no AS ID_NO, " + "staff_info.s_id AS Account " + " FROM staff_info,position " + " WHERE staff_info.posi_guid = position.guid " + " AND position.name = '" + tab_PosList.getValueAt(this.tab_PosList.getSelectedRow(), 0).toString() + "' " + " AND staff_info.exist = 1 ORDER BY s_id"; } rs_Pos = DBC.executeQuery(sql); if (rs_Pos.next()) { tab_PosDetail.setModel(HISModel.getModel(rs_Pos, null)); } else { tab_PosDetail.setModel( getModle( new String[] {"Message"}, new String[][] {{paragraph.getLanguage(line, "NOFORMATION")}})); // 將表格清空 } } catch (SQLException e) { ErrorMessage.setData( "Staff", "Frm_ Position", "showTables()", e.toString().substring(e.toString().lastIndexOf(".") + 1, e.toString().length())); System.out.println(e); } }
/** * Fetch the number of rows contained in this table. * * <p>returns -1 if unable to successfully fetch the row count * * @param db Database * @return int * @throws SQLException */ protected int fetchNumRows() { if (properties == null) // some "meta" tables don't have associated properties return 0; SQLException originalFailure = null; String sql = properties.getProperty("selectRowCountSql"); if (sql != null) { PreparedStatement stmt = null; ResultSet rs = null; try { stmt = db.prepareStatement(sql, getName()); rs = stmt.executeQuery(); while (rs.next()) { return rs.getInt("row_count"); } } catch (SQLException sqlException) { // don't die just because this failed originalFailure = sqlException; } finally { if (rs != null) { try { rs.close(); } catch (SQLException exc) { } } if (stmt != null) { try { stmt.close(); } catch (SQLException exc) { } } } } // if we get here then we either didn't have custom SQL or it didn't work try { // '*' should work best for the majority of cases return fetchNumRows("count(*)", false); } catch (SQLException try2Exception) { try { // except nested tables...try using '1' instead return fetchNumRows("count(1)", false); } catch (SQLException try3Exception) { logger.warning( "Unable to extract the number of rows for table " + getName() + ", using '-1'"); if (originalFailure != null) logger.warning(originalFailure.toString()); logger.warning(try2Exception.toString()); logger.warning(try3Exception.toString()); return -1; } } }
/** Connects to the underlying database. */ @Override protected ConnectionEntry connectImpl( Env env, String host, String userName, String password, String dbname, int port, String socket, int flags, String driver, String url, boolean isNewLink) { if (isConnected()) { env.warning(L.l("Connection is already opened to '{0}'", this)); return null; } try { if (host == null || host.equals("")) { host = "localhost"; } if (driver == null || driver.equals("")) { driver = "org.postgresql.Driver"; } if (url == null || url.equals("")) { url = "jdbc:postgresql://" + host + ":" + port + "/" + dbname; } ConnectionEntry jConn; jConn = env.getConnection(driver, url, userName, password, !isNewLink); return jConn; } catch (SQLException e) { env.warning("A link to the server could not be established. " + e.toString()); env.setSpecialValue("postgres.connectErrno", LongValue.create(e.getErrorCode())); env.setSpecialValue("postgres.connectError", env.createString(e.getMessage())); log.log(Level.FINE, e.toString(), e); return null; } catch (Exception e) { env.warning("A link to the server could not be established. " + e.toString()); env.setSpecialValue("postgres.connectError", env.createString(e.getMessage())); log.log(Level.FINE, e.toString(), e); return null; } }
@Override public Answer update(BuildRevisionBatch buildRevisionBatch) { MessageEvent msg = null; final String query = "UPDATE buildrevisionbatch SET system = ?, Country = ?, Environment = ?, Build = ?, Revision = ?, " + "Batch = ? WHERE id = ? "; // Debug message on SQL. if (LOG.isDebugEnabled()) { LOG.debug("SQL : " + query); } Connection connection = this.databaseSpring.connect(); try { PreparedStatement preStat = connection.prepareStatement(query); try { preStat.setString(1, buildRevisionBatch.getSystem()); preStat.setString(2, buildRevisionBatch.getCountry()); preStat.setString(3, buildRevisionBatch.getEnvironment()); preStat.setString(4, buildRevisionBatch.getBuild()); preStat.setString(5, buildRevisionBatch.getRevision()); preStat.setString(6, buildRevisionBatch.getBatch()); preStat.setLong(7, buildRevisionBatch.getId()); preStat.executeUpdate(); msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK); msg.setDescription( msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "UPDATE")); } catch (SQLException exception) { LOG.error("Unable to execute query : " + exception.toString()); msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED); msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString())); } finally { preStat.close(); } } catch (SQLException exception) { LOG.error("Unable to execute query : " + exception.toString()); msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED); msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString())); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException exception) { LOG.error("Unable to close connection : " + exception.toString()); } } return new Answer(msg); }
@Override public void createSoapLibrary(SoapLibrary soapLibrary) throws CerberusException { boolean throwExcep = false; StringBuilder query = new StringBuilder(); query.append( "INSERT INTO soaplibrary (`Type`, `Name`, `Envelope`, `Description`, `ServicePath`, `ParsingAnswer`, `Method`) "); query.append("VALUES (?,?,?,?,?,?,?);"); Connection connection = this.databaseSpring.connect(); try { PreparedStatement preStat = connection.prepareStatement(query.toString()); try { preStat.setString(1, soapLibrary.getType()); preStat.setString(2, soapLibrary.getName()); preStat.setString(3, soapLibrary.getEnvelope()); preStat.setString(4, soapLibrary.getDescription()); preStat.setString(5, soapLibrary.getServicePath()); preStat.setString(6, soapLibrary.getParsingAnswer()); preStat.setString(7, soapLibrary.getMethod()); preStat.executeUpdate(); throwExcep = false; } catch (SQLException exception) { MyLogger.log( SoapLibraryDAO.class.getName(), Level.ERROR, "Unable to execute query : " + exception.toString()); } finally { preStat.close(); } } catch (SQLException exception) { MyLogger.log( SoapLibraryDAO.class.getName(), Level.ERROR, "Unable to execute query : " + exception.toString()); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException e) { MyLogger.log(SoapLibraryDAO.class.getName(), Level.WARN, e.toString()); } } if (throwExcep) { throw new CerberusException(new MessageGeneral(MessageGeneralEnum.CANNOT_UPDATE_TABLE)); } }
@Override public Answer update(SoapLibrary object) { MessageEvent msg = null; final String query = "UPDATE soaplibrary sol SET Type = ?, `ServicePath` = ?, `Method` = ?, Envelope = ?, ParsingAnswer = ?, Description = ? WHERE Name = ?"; // Debug message on SQL. if (LOG.isDebugEnabled()) { LOG.debug("SQL : " + query); } Connection connection = this.databaseSpring.connect(); try { PreparedStatement preStat = connection.prepareStatement(query); try { preStat.setString(1, object.getType()); preStat.setString(2, object.getServicePath()); preStat.setString(3, object.getMethod()); preStat.setString(4, object.getEnvelope()); preStat.setString(5, object.getParsingAnswer()); preStat.setString(6, object.getDescription()); preStat.setString(7, object.getName()); preStat.executeUpdate(); msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK); msg.setDescription( msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "UPDATE")); } catch (SQLException exception) { LOG.error("Unable to execute query : " + exception.toString()); msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED); msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString())); } finally { preStat.close(); } } catch (SQLException exception) { LOG.error("Unable to execute query : " + exception.toString()); msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED); msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString())); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException exception) { LOG.warn("Unable to close connection : " + exception.toString()); } } return new Answer(msg); }
/** * Eliminar un registro. * * @param inTproc Object - Objeto procesado * @throws PersistenciaException - capa de persistencia * @return Object - identificador de objeto */ public Object delete(Object par_municipio) throws PersistenciaException { PreparedStatement stmt = null; Connection connection = null; StringBuffer sqlString = new StringBuffer(); Par_MunicipioTO par_municipioTO = (Par_MunicipioTO) par_municipio; sqlString.append(" DELETE FROM SPAR_MUNICIPIO"); sqlString.append(" WHERE MPIO_ID=?"); try { synchronized (this) { connection = super.getConnection(this.objDataSession); stmt = connection.prepareStatement(sqlString.toString()); int i = 1; setLong(stmt, (Long) par_municipioTO.getAttribute(Par_MunicipioTO.MPIO_ID), i++); stmt.executeUpdate(); } return "Ok"; } catch (SQLException ex) { System.err.println("error Par_MunicipioDAO.delete: " + ex.toString()); throw new PersistenciaException(ex.getMessage(), ex); } finally { try { super.cerrarConexiones(connection, stmt, null, this.objDataSession); } catch (Exception ex) { ex.printStackTrace(); } } }
private static boolean saverequest(String userid, String dtbase, int subcode) { Connection connection = null; PreparedStatement statement = null; DBPool dbpool = new DBPool(); try { connection = dbpool.getConnectionGateway(); if (connection == null) { Util.logger.error("Impossible to connect to DB"); return false; } String sqlInsert = "INSERT INTO " + dtbase + "(userid, subcode) VALUES ('" + userid + "'," + subcode + ")"; Util.logger.info("Insert:" + sqlInsert); statement = connection.prepareStatement(sqlInsert); if (statement.execute()) { Util.logger.error("Insert into dbcontent"); return false; } return true; } catch (SQLException e) { Util.logger.error(": Error:" + e.toString()); return false; } catch (Exception e) { Util.logger.error(": Error:" + e.toString()); return false; } finally { dbpool.cleanup(statement); dbpool.cleanup(connection); } }
public static void closeAll() { try { conn.close(); } catch (SQLException ex) { metrixLogger.log.log(Level.SEVERE, "Error closing SQL Connection! {0}", ex.toString()); } }
private Test(String driver, String url, String user, String password, boolean writeDelay0) { this.url = url; try { Class.forName(driver); conn = DriverManager.getConnection(url, user, password); stat = conn.createStatement(); if (writeDelay0) { stat.execute("SET WRITE_DELAY 0"); } System.out.println(url + " started"); } catch (Exception e) { System.out.println(url + ": " + e.toString()); return; } try { ResultSet rs = stat.executeQuery("SELECT MAX(ID) FROM TEST"); rs.next(); System.out.println(url + ": MAX(ID)=" + rs.getInt(1)); stat.execute("DROP TABLE TEST"); } catch (SQLException e) { // ignore } try { stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)"); } catch (SQLException e) { System.out.println(url + ": " + e.toString()); } }
public QUANTRI getQuanTri(String id) { // TODO Auto-generated method stub ResultSet rs = db.getResultSet( "select IdQuanTri,QuyenQuanTri,TAIKHOAN.TenTaiKhoan,MatKhau,HoTen,TAIKHOAN.DiaChi,DienThoai,Email,CHINHANH.IdChiNhanh,TenChiNhanh,CHINHANH.DiaChi" + " from QUANTRI join TAIKHOAN on QUANTRI.TenTaiKhoan=TAIKHOAN.TenTaiKhoan" + " join CHINHANH on QUANTRI.IdChiNhanh=CHINHANH.IdChiNhanh where IdQuanTri=N'" + id + "'"); QUANTRI quantri = new QUANTRI(); try { if (rs.next()) { quantri.setIdQuanTri(rs.getString(1)); quantri.setQuyenQuanTri(rs.getString(2)); quantri.setTaiKhoan( new TAIKHOAN( rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8))); quantri.setChiNhanh(new CHINHANH(rs.getString(9), rs.getString(10), rs.getString(11))); } } catch (SQLException e) { System.out.println(e.toString()); } return quantri; }
// 查詢資料 // 可以看看回傳結果集及取得資料方式 private JSONObject SelectTable(JSONObject jsonObject) throws Exception { try { String selectSQL = jsonObject.getString("sqlCommand"); JSONArray keys = jsonObject.getJSONArray("keys"); JSONArray jsonArray = new JSONArray(); JSONObject result = new JSONObject(); stat = con.createStatement(); rs = stat.executeQuery(selectSQL); while (rs.next()) { HashMap<String, String> hashMap = new HashMap<String, String>(); for (int i = 0; i < keys.length(); i++) { hashMap.put(keys.getString(i), rs.getString(keys.getString(i))); } jsonArray.put(hashMap); } try { result.put("RESULT", jsonArray); return result; } catch (Exception e) { return null; } } catch (SQLException e) { System.out.println("DropDB Exception :" + e.toString()); return null; } finally { Close(); } }
public JSONObject SelectKeyword(JSONObject jsonObject) throws Exception { try { String selectSQL = jsonObject.getString("sqlCommand"); JSONArray keys = jsonObject.getJSONArray("keys"); JSONArray jsonArray = new JSONArray(); JSONObject result = new JSONObject(); stat = con.createStatement(); rs = stat.executeQuery(selectSQL); if (rs.next() == false) { return null; } result.put("seg_dic_id", rs.getString("seg_dic_id")); for (int i = 0; i < keys.length(); i++) { jsonArray.put(rs.getString(keys.getString(i))); } try { result.put("values", jsonArray); return result; } catch (Exception e) { return null; } } catch (SQLException e) { System.out.println("DropDB Exception :" + e.toString()); return null; } finally { Close(); } }
@Override public String update(Object obj) { Connection cn; PreparedStatement pst; String sql; String sqlresp = null; MstGasto gasto = (MstGasto) obj; try { Class.forName(bd.getDriver()); cn = DriverManager.getConnection(bd.getUrl(), bd.getUser(), bd.getPasswd()); sql = "update mst_tipo_gastos set desc_gasto=?, cod_cta_conta=?, valor_gasto=?, fecha_creacion=? cod_usuario=? activo=? where cod_residencial=? and corr_gasto=?"; pst = cn.prepareStatement(sql); pst.setString(1, gasto.getDesc_gasto()); pst.setString(2, gasto.getCod_cta_conta()); pst.setDouble(3, gasto.getValor_gasto()); pst.setDate(4, gasto.getFecha_creacion()); pst.setString(5, gasto.getCod_usuario()); pst.setString(6, gasto.getActivo()); pst.setInt(7, gasto.getCod_residencial()); pst.setInt(8, gasto.getCorr_gasto()); int registro = pst.executeUpdate(); sqlresp = registro + " registro ha sido modificado."; pst.close(); cn.close(); } catch (SQLException e) { log.severe(e.toString()); } catch (Exception e) { log.severe(e.toString()); } return sqlresp; }
public long crearTicket() { long incremento = this.iniciarTicket(); if (incremento > 0) { incremento = (incremento + 1); String sql = "INSERT INTO cartera (id_correlativo_cart,ticket_cart,user_sistema,estatus) VALUES (" + incremento + ",'TIC-" + incremento + "','" + Usuario.getUser().getLogin() + "',0)"; try { Statement stmt = Conexion.getSratement(); stmt.executeUpdate(sql); return incremento; } catch (SQLException e) { System.out.println(e.toString()); return -1; } } else { System.out.println("incremento " + incremento); return -1; } }
private long iniciarTicket() { long correlativo = 0; try { String sql = "SELECT MAX(id_correlativo_cart) as tik FROM cartera"; Statement stmt = Conexion.getSratement(); ResultSet rset = stmt.executeQuery(sql); if (rset.next()) { correlativo = rset.getLong("tik"); if (correlativo == 0) { // cuando no hay registros hay que crear uno correlativo = 1000; } } // System.out.println(correlativo); rset.close(); return correlativo; } catch (SQLException e) { System.out.println("iniciar ticket " + e.toString()); return -1; } }
public ResultSet eseguiQueryStatement(PreparedStatement statement) throws SystemError { try { return statement.executeQuery(); } catch (SQLException ex) { throw new SystemError(ex.toString(), MODULO, "eseguiQueryStatement", ex); } }
/** * Authenticates to the Database Server using the provided bind request. * * @param request The bind request. * @return The result of the operation. * @throws ErrorResultException If the result code indicates that the request failed for some * reason. * @throws ClassNotFoundException If no definition for the class with the specified driver name * could be found. * @throws SQLException If the driver could not establish a connection with the Database Server. */ @Override public BindResult bind(final BindRequest request) throws ErrorResultException { BindResult r; // Extract user name and password from the bind request. final String userName = request.getName(); final String userPass; byte[] password = null; if (request instanceof SimpleBindRequest) { password = ((SimpleBindRequest) request).getPassword(); } else { r = Responses.newBindResult(ResultCode.PROTOCOL_ERROR); return r; } userPass = new String(password); // Establish SQL connection to the Database Server. try { Class.forName(driverName); this.connection = DriverManager.getConnection(this.connectionUrl, userName, userPass); } catch (ClassNotFoundException e) { System.out.println(e.toString()); r = Responses.newBindResult(ResultCode.OTHER); return r; } catch (SQLException e) { System.out.println(e.toString()); r = Responses.newBindResult(ResultCode.CLIENT_SIDE_CONNECT_ERROR); return r; } r = Responses.newBindResult(ResultCode.SUCCESS); return r; }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // String county= request.getParameter("county").toString(); String countyid = request.getParameter("countyid"); String id = request.getParameter("id"); String value = request.getParameter("value"); String columnName = request.getParameter("columnName"); String columnId = request.getParameter("columnId"); String columnPosition = request.getParameter("columnPosition"); String rowId = request.getParameter("rowId"); response.getWriter().print(value); HttpSession session; session = request.getSession(true); // String unique=(String)session.getAttribute("countyid"); dbConnect conn = new dbConnect(); String query = "update behaviourscode set BehavioursCode='" + value + "'where BehavioursCodeID='" + id + "'"; try { conn.state.executeUpdate(query); // response.sendRedirect("CountyServlet"); } catch (SQLException ex) { Logger.getLogger(UpdateBehaviour.class.getName()).log(Level.SEVERE, null, ex); out.println(ex.toString()); } }
@Override public String delete(Object obj) { Connection cn; PreparedStatement pst; String sql; String sqlresp = null; MstGasto gasto = (MstGasto) obj; try { Class.forName(bd.getDriver()); cn = DriverManager.getConnection(bd.getUrl(), bd.getUser(), bd.getPasswd()); sql = "delete from mst_tipo_gastos where cod_residencial=? and corr_gasto=?"; pst = cn.prepareStatement(sql); pst.setInt(1, gasto.getCod_residencial()); pst.setInt(2, gasto.getCorr_gasto()); int registro = pst.executeUpdate(); sqlresp = registro + " registro ha sido eliminado."; pst.close(); cn.close(); } catch (SQLException e) { log.severe(e.toString()); } catch (Exception e) { log.severe(e.toString()); } return sqlresp; }
public int eseguiUpdateStatement(PreparedStatement statement) throws SystemError { try { return statement.executeUpdate(); } catch (SQLException ex) { throw new SystemError(ex.toString(), MODULO, "eseguiUpdateStatement", ex); } }
@Override public String create(Object obj) { Connection cn; PreparedStatement pst; String sql; String sqlresp = null; MstGasto gasto = (MstGasto) obj; try { Class.forName(bd.getDriver()); cn = DriverManager.getConnection(bd.getUrl(), bd.getUser(), bd.getPasswd()); sql = "insert into mst_tipo_gastos values (?, ?, ?, ?, ?, ?, ?, ?)"; pst = cn.prepareStatement(sql); pst.setInt(1, gasto.getCod_residencial()); pst.setInt(2, gasto.getCorr_gasto()); pst.setString(3, gasto.getDesc_gasto()); pst.setString(4, gasto.getCod_cta_conta()); pst.setDouble(5, gasto.getValor_gasto()); pst.setDate(6, gasto.getFecha_creacion()); pst.setString(7, gasto.getCod_usuario()); pst.setString(8, gasto.getActivo()); int registro = pst.executeUpdate(); sqlresp = registro + " registro ha sido agregado."; pst.close(); cn.close(); } catch (SQLException e) { log.severe(e.toString()); } catch (Exception e) { log.severe(e.toString()); } return sqlresp; }
////// Renombrar a grabarPortalMaestro() public void guardarPortalGestionar(Collection<String[]> array) throws DAOException { log.info("guardarPortalGestionar(Collection<String[]> array)"); Connection cons = null; PreparedStatement stmt = null; try { String query = "update cv_servicio_maestro set columna=? , posicion=? where idservicio=?"; cons = dataSource.getConnection(); stmt = cons.prepareStatement(query); int posicion = 0; for (String[] item : array) { stmt.setInt(1, posicion++); for (int u = 0; u < item.length; u++) { stmt.setInt(2, u); stmt.setString(3, item[u]); stmt.executeUpdate(); } } } catch (SQLException e) { log.error(e); throw new DAOException(e.toString()); } catch (Exception e) { log.error(e); throw new DAOException(e.toString()); } finally { closeStatement(stmt); closeConnection(cons); } }
@Override public List<MstGasto> read() { Connection cn; PreparedStatement pst; ResultSet rs; String sql; List<MstGasto> lst = new ArrayList(); try { Class.forName(bd.getDriver()); cn = DriverManager.getConnection(bd.getUrl(), bd.getUser(), bd.getPasswd()); sql = "select * from mst_tipo_gastos order by corr_gasto"; pst = cn.prepareStatement(sql); rs = pst.executeQuery(); while (rs.next()) { lst.add( new MstGasto( rs.getInt("cod_residencial"), rs.getInt("corr_gasto"), rs.getString("desc_gasto"), rs.getString("cod_cta_conta"), rs.getDouble("valor_gasto"), rs.getDate("fecha_creacion"), rs.getString("cod_usuario"), rs.getString("activo"))); } rs.close(); pst.close(); cn.close(); } catch (SQLException e) { log.severe(e.toString()); } catch (Exception e) { log.severe(e.toString()); } return lst; }