/** * _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); } } }
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); } }
public void listProducts() { products = new ArrayList<Product>(); try { ResultSet results; if (listAllProducts) { results = listAllProductsStatement.executeQuery(); } else { listByCustomerStatement.setString(1, customerLogin); results = listByCustomerStatement.executeQuery(); } while (results.next()) { int auctionId = results.getInt("auction_id"); Product product = new Product(session.getDb(), auctionId); products.add(product); } } catch (SQLException e) { while (e != null) { debug.println(e.toString()); debug.flush(); e = e.getNextException(); } } if (products.size() <= 0) { productsBox.setLine(0, ""); productsBox.setLine(1, " No products to show."); for (int i = 2; i < 13; i++) { productsBox.setLine(i, ""); } } else { productsBox.setLine(0, " Name | Status | Highest Bid Amount | Buyer or Highest Bidder"); productsBox.setLine(1, ""); ArrayList<Product> productsOnPage = paginator.paginate(products, curPage, 5); int lineOffset = 0; for (int i = 0; i < productsOnPage.size(); i++) { Product product = productsOnPage.get(i); // lineOffset works now lineOffset = i * 2; productsBox.setLine( lineOffset + 3, " " + product.name + " | " + product.status + " | $" + product.amount + " | " + product.getHighestBidder()); } // clear the lines of productBox if there are not as many products as before int lastLine = productsOnPage.size() * 2 + 2; for (int i = lastLine; i < 12; i++) { productsBox.setLine(i, ""); } productsBox.setLine(12, paginator.getPageMenu(products, curPage, 5)); } }
public boolean Nuevo() { try { String OrdenSQL = "INSERT INTO Conaic_Area(id,area," + "subarea," + "subsubarea," + "nombre," + "clave," + "descripcion)" + "VALUES(?,?,?,?,?,?,?)"; // Se crea una orden con parametros this.bd.preparedstatement = this.bd.conexion.prepareStatement(OrdenSQL); // Obtenemos una matricula para asignar al nuevo alumno // Se establecen los valores que se van a enviar para insertar this.bd.preparedstatement.setInt(1, this.id); this.bd.preparedstatement.setInt(2, this.area); this.bd.preparedstatement.setInt(3, this.subarea); this.bd.preparedstatement.setInt(4, this.subsubarea); this.bd.preparedstatement.setString(5, this.nombre.toUpperCase()); this.bd.preparedstatement.setString(6, this.clave.toUpperCase()); this.bd.preparedstatement.setString(7, this.descripcion); this.bd.preparedstatement.executeUpdate(); return (true); } catch (SQLException Error) { JOptionPane.showMessageDialog( null, Error.getMessage() + "\n" + Error.toString(), "Error Clase Alumno", JOptionPane.ERROR_MESSAGE); } return (false); }
public ArrayList obtenerCriterioxCompetencia(int xId) { try { Statement stmt = null; ResultSet rs = null; ConexionBD connect = new ConexionBD(); Connection con = connect.getConnect(); ArrayList cc = new ArrayList(); // SQL query command String SQL = "SELECT * FROM tr_criterio_competencia where competencia_id = " + xId; stmt = con.createStatement(); rs = stmt.executeQuery(SQL); while (rs.next()) { cc.add( new CriterioCompetencia( rs.getInt("CRITERIO_COMPETENCIA_ID"), rs.getInt("CRITERIO_ID"), rs.getInt("COMPETENCIA_ID"))); } return cc; } catch (SQLException ex) { System.out.println("SQL Exception: " + ex.toString()); } return null; }
public static void closeConnect() { try { con.close(); } catch (SQLException e) { MessageBox.infoBox(e.toString(), "Error in closeConnect"); } }
public boolean atualizaUsuario( int codigo, String nome, String login, String senha, String permissao) { String sql; conecta(); try { sql = "UPDATE usuario SET nome='" + nome + "', login='******', " + "senha='" + senha + "', permissao='" + permissao + "' WHERE codigo=" + codigo + ";"; System.out.println(sql); stmt.executeUpdate(sql); return true; } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Erro ao executar o comando SQL:" + e.toString()); return false; } }
@SuppressWarnings("unchecked") protected void BindRow() { try { view_plantillas_modulo pNode = new view_plantillas_modulo(); pNode.setID_Plantilla(m_RS.getInt("ID_Plantilla")); pNode.setbID_Empleado(m_RS.getBoolean("bID_Empleado")); pNode.setbNomina(m_RS.getBoolean("bNomina")); pNode.setbTipo_Nomina(m_RS.getBoolean("bTipo_Nomina")); pNode.setbCompania_Sucursal(m_RS.getBoolean("bCompania_Sucursal")); pNode.setCompania(m_RS.getString("Compania")); pNode.setFecha(m_RS.getDate("Fecha")); pNode.setID_Movimiento(m_RS.getInt("ID_Movimiento")); pNode.setID_Empleado(m_RS.getString("ID_Empleado")); pNode.setMovimiento(m_RS.getString("Movimiento")); pNode.setDescripcion(m_RS.getString("Descripcion")); pNode.setAplicacion(m_RS.getString("Aplicacion")); pNode.setCalcular(m_RS.getBoolean("Calcular")); m_Rows.addElement(pNode); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e.toString()); } }
@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; }
/** * 使用 ResultSet 中的第 i 行给 Schema 赋值 * * @param: rs ResultSet * @param: i int * @return: boolean */ public boolean setSchema(ResultSet rs, int i) { try { // rs.absolute(i); // 非滚动游标 if (rs.getString("CalCode") == null) this.calCode = null; else this.calCode = rs.getString("CalCode").trim(); if (rs.getString("RiskCode") == null) this.riskCode = null; else this.riskCode = rs.getString("RiskCode").trim(); if (rs.getString("Type") == null) this.type = null; else this.type = rs.getString("Type").trim(); if (rs.getString("CalSQL") == null) this.calSQL = null; else this.calSQL = rs.getString("CalSQL").trim(); if (rs.getString("Remark") == null) this.remark = null; else this.remark = rs.getString("Remark").trim(); } catch (SQLException sqle) { System.out.println( "数据库中的LEPCalMode表字段个数和Schema中的字段个数不一致,或者执行db.executeQuery查询时没有使用select * from tables"); // @@错误处理 CError tError = new CError(); tError.moduleName = "LEPCalModeSchema"; tError.functionName = "setSchema"; tError.errorMessage = sqle.toString(); this.mErrors.addOneError(tError); return false; } return true; }
@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; }
public String getAlertas(String cod_empresa) { String sql = "SELECT * FROM alertas WHERE cod_empresa="; sql += cod_empresa + " ORDER BY alerta"; String resp = ""; try { // Cria statement para enviar sql stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = null; // Executa a pesquisa rs = stmt.executeQuery(sql); // Cria looping com a resposta while (rs.next()) { resp += "<option value='" + rs.getString("cod_alerta") + "'>" + rs.getString("alerta") + "</option>\n"; } rs.close(); stmt.close(); return resp; } catch (SQLException e) { return e.toString(); } }
/* Constructeur : ouvre la connexion */ private ConnexionMySQL() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException classe) { System.out.println(classe.toString()); } connected = false; url = "jdbc:mysql://localhost/tfe_memoir"; // en local // String url = "jdbc:mysql://sql.info.iepscf-uccle.be/sonneville"; //à l'école try { /* setup the properties: si les accents ne sont pas Unicode ds la BDD java.util.Properties prop = new java.util.Properties(); prop.put("charSet", "ISO-8859-15"); prop.put("user", username); prop.put("password", password);*/ // Connect to the database conn = DriverManager.getConnection(url, "root", ""); // en local // conn=DriverManager.getConnection(url, "sonneville",""); // à l'école stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); // on peut parcourir le résultat dans les 2 sens, insensible aux chgmts d'autrui // on peut modifier ce résultat pour ensuite reporter ces modifs ds la table (updateRow) conn.setAutoCommit(false); connected = true; } catch (SQLException e) { System.out.println(e.toString()); } }
@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; }
/** * 使用 ResultSet 中的第 i 行给 Schema 赋值 * * @param: rs ResultSet * @param: i int * @return: boolean */ public boolean setSchema(ResultSet rs, int i) { try { // rs.absolute(i); // 非滚动游标 if (rs.getString("RiskCode") == null) this.riskCode = null; else this.riskCode = rs.getString("RiskCode").trim(); if (rs.getString("RiskVer") == null) this.riskVer = null; else this.riskVer = rs.getString("RiskVer").trim(); if (rs.getString("DutyCode") == null) this.dutyCode = null; else this.dutyCode = rs.getString("DutyCode").trim(); if (rs.getString("ChoFlag") == null) this.choFlag = null; else this.choFlag = rs.getString("ChoFlag").trim(); if (rs.getString("SpecFlag") == null) this.specFlag = null; else this.specFlag = rs.getString("SpecFlag").trim(); } catch (SQLException sqle) { System.out.println( "数据库中的LEPRiskDuty表字段个数和Schema中的字段个数不一致,或者执行db.executeQuery查询时没有使用select * from tables"); // @@错误处理 CError tError = new CError(); tError.moduleName = "LEPRiskDutySchema"; tError.functionName = "setSchema"; tError.errorMessage = sqle.toString(); this.mErrors.addOneError(tError); return false; } return true; }
/** * Execute an insert statement * * @param query */ public long insert(String query) { if (PreciousStones.getInstance().getSettingsManager().isDebugsql()) { PreciousStones.getLog().info(query); } try { Statement statement = getConnection().createStatement(); ResultSet keys = null; try { statement.executeUpdate(query); keys = statement.executeQuery("SELECT last_insert_rowid()"); } finally { if (keys != null) { if (keys.next()) { return keys.getLong(1); } } statement.close(); return 0; } } catch (SQLException ex) { if (!ex.toString().contains("not return ResultSet")) { log.severe("Error at SQL INSERT Query: " + ex); log.severe("Query: " + query); } } return 0; }
@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; }
/** * 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 username = request.getParameter("username"); String password = request.getParameter("password"); Statement stmt; ResultSet rs; Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); String connectionUrl = "jdbc:mysql://localhost/myflickr?" + "user=root&password=123456"; con = DriverManager.getConnection(connectionUrl); if (con != null) { System.out.println("connected to mysql"); } } catch (SQLException e) { System.out.println("SQL Exception: " + e.toString()); } catch (ClassNotFoundException cE) { System.out.println("Class Not Found Exception: " + cE.toString()); } try { stmt = con.createStatement(); System.out.println("SELECT * FROM flickrusers WHERE name='" + username + "'"); rs = stmt.executeQuery("SELECT * FROM flickrusers WHERE name='" + username + "'"); while (rs.next()) { if (rs.getObject(1).toString().equals(username)) { out.println("<h1>To username pou epileksate uparxei hdh</h1>"); out.println("<a href=\"project3.html\">parakalw dokimaste kapoio allo.</a>"); stmt.close(); rs.close(); return; } } stmt.close(); rs.close(); stmt = con.createStatement(); if (!stmt.execute("INSERT INTO flickrusers VALUES('" + username + "', '" + password + "')")) { out.println("<h1>Your registration is completed " + username + "</h1>"); out.println("<a href=\"index.jsp\">go to the login menu</a>"); registerListener.Register(username); } else { out.println("<h1>To username pou epileksate uparxei hdh</h1>"); out.println("<a href=\"project3.html\">Register</a>"); } } catch (SQLException e) { throw new ServletException("Servlet Could not display records.", e); } }
/* ferme la connexion. */ public void close() { try { conn.close(); connected = false; } catch (SQLException e) { System.out.println(e.toString()); } }
public void endDocument() throws SAXException { // System.out.println("endDocument()"); try { conn_.commit(); closeDatabase(); } catch (SQLException sqle) { throw new SAXException(sqle.toString()); } }
private void submitButtonActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_submitButtonActionPerformed // TODO add your handling code here: Connection con = FrameLogin.getConnect(); String SQLInsert = "INSERT INTO `2761DB`.`Persons` (`FirstName`, `LastName`, `CellPhoneNo`, `HomePhoneNo`, " + "`SchoolId`, `Graduation Year`, `Gender`) VALUES ('" + firstName.getText() + "', '" + lastName.getText() + "', '" + cellPhone.getText() + "', '" + homePhone.getText() + "', '" + studentId.getText() + "', '" + gradYear.getText() + "', '" + (String) (gender.getSelectedItem()) + "');"; String SQLUpdate = "UPDATE `2761DB`.`Persons` SET `FirstName` = '" + firstName.getText() + "', `LastName` = '" + lastName.getText() + "', `CellPhoneNo` = ' " + cellPhone.getText() + "', `HomePhoneNo` = '" + homePhone.getText() + "', `Graduation Year` = '" + gradYear.getText() + "', `Gender` = '" + (String) (gender.getSelectedItem()) + "' WHERE `PersonId` = '" + Id + "';"; // UPDATE `2761DB`.`Persons` SET `FirstName`='Robbie', `LastName`='Tacescu', `CellPhoneNo`='', // `HomePhoneNo`='559300', `SchoolId`='15648916', `Graduation Year`='6545', `Gender`='males' // WHERE // `PersonId`='42'; try { if (isEdit) { Statement stmt = con.createStatement(); // System.out.println(SQLUpdate); stmt.executeUpdate(SQLUpdate); } else { Statement stmt = con.createStatement(); // System.out.println(SQLInsert); stmt.executeUpdate(SQLInsert); } } catch (SQLException err) { MessageBox.infoBox(err.toString(), "Error in AddUserForm submitButton"); } FrameLogin.closeConnect(); this.dispose(); } // GEN-LAST:event_submitButtonActionPerformed
public void initTables() { ResultSet rs = null; try { rs = DBC.executeQuery("SELECT name FROM position"); this.tab_PosList.setModel( new TableModels(rs, new String[] {paragraph.getLanguage(line, "POSITIONNAME")})); } catch (SQLException e) { ErrorMessage.setData( "Staff", "Frm_ Position", "initTables()", e.toString().substring(e.toString().lastIndexOf(".") + 1, e.toString().length())); System.out.println(e); } tab_PosDetail.setModel( getModle( new String[] {paragraph.getLanguage(line, "MESSAGE")}, new String[][] {{paragraph.getLanguage(line, "NOINFORMATION")}})); }
private void jButton1ActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed String no = jTextField1.getText(); String csec = jTextField2.getText(); String dept = jComboBox1.getSelectedItem().toString(); int floor = Integer.parseInt(jComboBox2.getSelectedItem().toString()); String seat = jTextField5.getText(); System.out.println(no); System.out.println(csec); System.out.println(dept); System.out.println(floor); System.out.println(seat); if (no.equals("") || csec.equals("") || dept.equals("") || seat.equals("")) { jDialog1.setVisible(true); jDialog1.show(); jDialog1.pack(); } else { try { Class.forName("com.mysql.jdbc.Driver"); String connectionUrl = "jdbc:mysql://localhost/exam_man?" + "user=root&password=root"; Connection con = (Connection) DriverManager.getConnection(connectionUrl); Statement stmt = null; stmt = con.createStatement(); String query = "insert into rooms(No,Class_Section,Dept,Floor,Seating_Capacity) values('" + no + "','" + csec + "','" + dept + "'," + floor + ",'" + seat + "')"; stmt.executeUpdate(query); jDialog2.setVisible(true); jDialog2.pack(); this.setVisible(false); con.close(); } catch (SQLException e) { System.out.println("SQL Exception:" + e.toString()); } catch (ClassNotFoundException ce) { System.out.println("Class Not Found Exception:" + ce.toString()); } } } // GEN-LAST:event_jButton1ActionPerformed
/*Cette fct permet d'exécuter une requête d'action. */ public boolean actionQuery(String query) { boolean b = false; try { stat.executeUpdate(query); b = true; conn.commit(); // force à exécuter la requête sur la BDD } catch (SQLException e) { System.out.println(e.toString()); System.out.println("Requete :" + query); } return b; }
public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); String connectionUrl = "jdbc:mysql://localhost/mysql?" + "user=root&password=root"; Connection con = DriverManager.getConnection(connectionUrl); } catch (SQLException e) { System.out.println("SQL Exception: " + e.toString()); } catch (ClassNotFoundException cE) { System.out.println("Class Not Found Exception: " + cE.toString()); } }
public void close() { try { basicstmt.close(); DatabaseFactory.freeConnection(corecxn); DatabaseFactory.freeConnection(chipcxn); corecxn = null; chipcxn = null; basicstmt = null; } catch (SQLException e) { throw new DatabaseException(e.toString(), e); } }
// Recupera todos os alertas do paciente para criar select box public String getAlertasPaciente(String codcli) { String sql = ""; String resp = ""; ResultSet rs = null; int cont = 1; try { // Cria statement para enviar sql stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); sql += "SELECT alertas.*, alerta_paciente.* "; sql += "FROM alerta_paciente INNER JOIN alertas ON "; sql += "alerta_paciente.cod_alerta = alertas.cod_alerta "; sql += "WHERE alerta_paciente.cod_paci='" + codcli + "'"; // Executa a pesquisa rs = stmt.executeQuery(sql); // Cabeçalho resp += "<table cellspacing=0 cellpadding=0 width='100%'>\n"; resp += "<tr>\n"; resp += " <td class='tdMedium'><b>nº</b></td>\n"; resp += " <td class='tdMedium'><b>Alertas</b></td>\n"; resp += " <td class='tdMedium'><b>Início</b></td>\n"; resp += " <td class='tdMedium'><b>Fim</b></td>\n"; resp += " <td class='tdMedium'><b>Excluir</b></td>\n"; resp += "</tr>\n"; // Cria looping com a resposta while (rs.next()) { resp += "<tr>\n"; resp += " <td class='tdLight'>Alerta " + cont + "</td>\n"; resp += " <td class='tdLight'>" + rs.getString("alerta") + "</td>\n"; resp += " <td class='tdLight'>" + Util.formataData(rs.getString("de")) + " </td>\n"; resp += " <td class='tdLight'>" + Util.formataData(rs.getString("ate")) + " </td>\n"; resp += " <td class='tdLight' align='center'><a title='Excluir alerta' href='Javascript:excluiralerta(" + rs.getString("cod_alerta_paci") + ")'><img src='images/delete.gif' border=0></a></td>\n"; resp += "</tr>\n"; cont++; } resp += "</table>"; rs.close(); stmt.close(); return resp; } catch (SQLException e) { return "ERRO: " + e.toString() + " SQL=" + sql; } }
public static void main(String[] args) { HashMap<Integer, SolarSystem> systems; ArrayList<SolarSystemJump> jumps; try { EveDB db = new EveDB(); systems = db.getSolarSystems(); jumps = db.getSolarSystemJumps(); } catch (SQLException e) { System.out.println(e.toString()); return; } UniverseGraph map = new UniverseGraph(systems.values(), jumps); }
private void btn_PosDelActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btn_PosDelActionPerformed Object getValue = tab_PosList.getValueAt(tab_PosList.getSelectedRow(), 0); String sql = "DELETE FROM position WHERE name = '" + getValue.toString() + "'"; Object[] options = { paragraph.getLanguage(message, "YES"), paragraph.getLanguage(message, "NO") }; int response = JOptionPane.showOptionDialog( new Frame(), paragraph.getLanguage(message, "DOYOUWANTTODELETE"), paragraph.getLanguage(message, "MESSAGE"), JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (response == 0) { try { DBC.executeUpdate(sql); } catch (SQLException e) { ErrorMessage.setData( "Staff", "Frm_ Position", "btn_PosDelActionPerformed()", e.toString().substring(e.toString().lastIndexOf(".") + 1, e.toString().length())); } } tab_PosDetail.setModel( getModle( new String[] {"Message"}, new String[][] {{paragraph.getLanguage(line, "NOFORMATION")}})); // 將表格清空 initTables(); this.btn_PosDel.setEnabled(false); this.btn_PosUpdate.setEnabled(false); this.btn_StaffPosUpdata.setEnabled(false); } // GEN-LAST:event_btn_PosDelActionPerformed
/** * 使用 ResultSet 中的第 i 行给 Schema 赋值 * * @param: rs ResultSet * @param: i int * @return: boolean */ public boolean setSchema(ResultSet rs, int i) { try { // rs.absolute(i); // 非滚动游标 if (rs.getString("recommend") == null) this.recommend = null; else this.recommend = rs.getString("recommend").trim(); if (rs.getString("recommended") == null) this.recommended = null; else this.recommended = rs.getString("recommended").trim(); this.sendtimes = rs.getInt("sendtimes"); if (rs.getString("success") == null) this.success = null; else this.success = rs.getString("success").trim(); if (rs.getString("registered") == null) this.registered = null; else this.registered = rs.getString("registered").trim(); if (rs.getString("field1") == null) this.field1 = null; else this.field1 = rs.getString("field1").trim(); if (rs.getString("field2") == null) this.field2 = null; else this.field2 = rs.getString("field2").trim(); if (rs.getString("field3") == null) this.field3 = null; else this.field3 = rs.getString("field3").trim(); if (rs.getString("makedate") == null) this.makedate = null; else this.makedate = rs.getString("makedate").trim(); if (rs.getString("maketime") == null) this.maketime = null; else this.maketime = rs.getString("maketime").trim(); if (rs.getString("modifydate") == null) this.modifydate = null; else this.modifydate = rs.getString("modifydate").trim(); if (rs.getString("modifytime") == null) this.modifytime = null; else this.modifytime = rs.getString("modifytime").trim(); } catch (SQLException sqle) { System.out.println( "数据库中的LECRecommendation表字段个数和Schema中的字段个数不一致,或者执行db.executeQuery查询时没有使用select * from tables"); // @@错误处理 CError tError = new CError(); tError.moduleName = "LECRecommendationSchema"; tError.functionName = "setSchema"; tError.errorMessage = sqle.toString(); this.mErrors.addOneError(tError); return false; } return true; }