public void actionPerformed(ActionEvent ev) { try { // stok String query = "DELETE FROM stok_produk WHERE id_produk=" + idProduk; int hasil1 = stm.executeUpdate(query); // pemasukkan query = "DELETE FROM pemasukan WHERE id_produk=" + idProduk; int hasil2 = stm.executeUpdate(query); // pengeluaran query = "DELETE FROM pengeluaran WHERE id_produk=" + idProduk; int hasil3 = stm.executeUpdate(query); // produk query = "DELETE FROM produk WHERE id_produk=" + idProduk; int hasil4 = stm.executeUpdate(query); if (hasil1 == 1 || hasil2 == 1 || hasil3 == 1 && hasil4 == 1) { setDataTabel(); JOptionPane.showMessageDialog(null, "berhasil hapus"); } else { JOptionPane.showMessageDialog(null, "gagal"); } } catch (SQLException SQLerr) { SQLerr.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
private String getInfo(ResultSet rs) throws SQLException { // position to first record boolean moreRecords = rs.next(); // If there are no records, display a message if (!moreRecords) { return null; } Vector columnHeads = new Vector(); Vector rows = new Vector(); try { // get column heads ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); ++i) columnHeads.addElement(rsmd.getColumnName(i)); // get row data do { rows.addElement(getNextRow(rs, rsmd)); } while (rs.next()); String info; String aux = rows.get(0).toString(); info = aux.substring(1, aux.length() - 1); return info; } catch (SQLException sqlex) { sqlex.printStackTrace(); return null; } }
@Override public List<Producto> readForName(String name) { List<Producto> lista = new ArrayList<Producto>(); Connection cn = null; try { cn = AccesoDB.getConnection(); String query = "select idprod, idcat, nombre, precio, stock " + "from producto " + "where upper(nombre) like ?"; PreparedStatement pstm = cn.prepareStatement(query); name = "%" + name.toUpperCase() + "%"; pstm.setString(1, name); ResultSet rs = pstm.executeQuery(); while (rs.next()) { Producto o = rsToBean(rs); lista.add(o); } rs.close(); pstm.close(); } catch (SQLException e) { throw new RuntimeException(e.getMessage()); } catch (Exception e) { throw new RuntimeException("No se puede consultar la base de datos."); } finally { try { cn.close(); } catch (Exception e) { } } return lista; }
@Override public Client search(int id) { ResultSet resultSet = null; try { preparedStatement = connection.prepareStatement("SELECT * FROM clients"); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { if (Integer.valueOf(resultSet.getString("id_client")) == id) { return new Client( resultSet.getString("name"), resultSet.getString("login"), resultSet.getString("phone"), resultSet.getString("email"), resultSet.getString("password")); } } } catch (SQLException e) { e.printStackTrace(); } return null; }
/** * Creates a new appointment. * * @param appointment which shall be inserted into the underlying persistance layer. must not be * null, id must be null * @return the given appointment for further usage * @throws PersistenceException if there are complications with the persitance layer */ @Override public Appointment create(Appointment appointment) throws PersistenceException { LOGGER.info("Creating a new appointment in db.. " + appointment); try { if (appointment == null) { LOGGER.error("Create parameter (appointment) was null."); throw new PersistenceException("Appointment to be create must not be null"); } Statement appointmentNextValStm = connection.createStatement(); ResultSet rs_appointmentNextVal = appointmentNextValStm.executeQuery("SELECT NEXTVAL('appointment_seq')"); rs_appointmentNextVal.next(); appointment.setId(rs_appointmentNextVal.getInt(1)); createStm.setInt(1, appointment.getId()); createStm.setDate(2, new java.sql.Date(appointment.getDatum().getTime())); createStm.setInt(3, appointment.getSession_id()); createStm.setInt(4, appointment.getUser_id()); createStm.setBoolean(5, appointment.getIsTrained()); createStm.setBoolean(6, appointment.getIsDeleted()); createStm.execute(); } catch (SQLException e) { LOGGER.error("Failed to create record into appointment table. - " + e.getMessage()); throw new PersistenceException("Failed to create record into appointment table.", e); } LOGGER.info("Record successfully created in appointment table."); return appointment; }
private boolean login(String[] part) { ResultSet rs = null; try { rs = beanOracle.selection("PASSWORD", "UTILISATEURS", "LOGIN = '******'"); } catch (SQLException e) { System.err.println(e.getStackTrace()); } String pwd = null; try { if (!rs.next()) { SendMsg("ERR#Login invalide"); } else pwd = rs.getString("PASSWORD"); } catch (SQLException ex) { System.err.println(ex.getStackTrace()); } if (pwd.equals(part[2])) { SendMsg("ACK"); return true; } else SendMsg("ERR#Mot de passe incorrecte"); return false; }
@Override public Emp get(Integer objectId) { if (conn == null) { System.err.println("No connect!!"); return null; } Emp emp = null; try { final String sql = "SELECT " + "id,lname,fname,mname,d_hire,d_fire " + "FROM DDT_EMP" + " WHERE id = ?"; PreparedStatement st = conn.prepareStatement(sql); st.setInt(1, objectId.intValue()); ResultSet rs = st.executeQuery(); while (rs.next()) { emp = new Emp(); emp.setId(rs.getInt("id")); emp.setLastName(rs.getString("lname")); emp.setFirstName(rs.getString("fname")); emp.setMiddleName(rs.getString("mname")); emp.setHireDate(rs.getDate("d_hire")); emp.setFireDate(rs.getDate("d_fire")); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return emp; }
public void addAttribute(DeweyID deweyID, String qName, int parentCID, boolean qNameFound) throws IOException, Exception { // parentCID is curNode's CID // logManager.LogManager.log(6,qName); // logManager.LogManager.log(6,"Attrib: "+deweyID.toString()); // logManager.LogManager.log(6,String.valueOf(deweyID.getCID())); // } // elemIndex.insert(deweyID.getCID(),deweyID); // bTreeIndex.insert(deweyID,deweyID.getCID(),qName); if (!qNameFound) { // structSumIndex.add(deweyID.getCID(),qName,parentCID); try { if (con != null) { String sqlQuery = "INSERT INTO \"OrderedByCID\" (\"CID\", \"DeweyID\") VALUES (?, ?);"; PreparedStatement pst = con.prepareStatement(sqlQuery); pst.setInt(1, deweyID.getCID()); pst.setString(2, deweyID.toString()); // pst.setString(3, String.v); pst.executeUpdate(); pst.close(); } } catch (SQLException e) { System.out.println("JDBC Driver is not Configured Correctly !"); e.printStackTrace(); return; } } // checkBufPool(); }
public boolean loadUserStatistics(Profile profile) { PreparedStatement ps = null; try { ps = database .getConnection() .prepareStatement( "SELECT wcaID, forumID FROM " + prefix + "user WHERE id=? LIMIT 1;"); ps.setInt(1, profile.getUser().getID()); ResultSet result = ps.executeQuery(); if (!result.next()) return false; profile.wcaID = result.getString("wcaID"); profile.forumID = result.getInt("forumID"); } catch (SQLException e) { e.printStackTrace(); } finally { closeOrFail(ps); } return true; }
public void deleteOption(String modelName, String optionSetName, String option) { try { int autoid = 0; String sql = "select id from automobile where name ='" + modelName + "';"; ResultSet rs; rs = statement.executeQuery(sql); while (rs.next()) { autoid = rs.getInt("id"); // get auto_id } int opsid = 0; sql = "select id from optionset where name ='" + optionSetName + "' and auto_id= " + autoid + ";"; rs = statement.executeQuery(sql); while (rs.next()) { opsid = rs.getInt("id"); // get option_id } sql = "delete from options where name= '" + option + "' and option_id= " + opsid; statement.executeUpdate(sql); // delete it using name and option_id } catch (SQLException e) { e.printStackTrace(); } }
public void updateOptionPrice( String modelName, String optionSetName, String optionName, float newPrice) { try { int autoid = 0; String sql = "select id from automobile where name ='" + modelName + "';"; ResultSet rs = statement.executeQuery(sql); while (rs.next()) { autoid = rs.getInt("id"); // get auto_id } int opsid = 0; sql = "select id from optionset where name ='" + optionSetName + "' and auto_id= " + autoid + ";"; rs = statement.executeQuery(sql); while (rs.next()) { opsid = rs.getInt("id"); // get option_id } sql = "update options set price = " + newPrice + " where name= '" + optionName + "' and option_id= " + opsid + ";"; statement.executeUpdate(sql); // update it with name and option_id } catch (SQLException e) { e.printStackTrace(); } }
/** * get a project by projectID * * @return a project */ public Project getProject(int ID) { PreparedStatement stmt = null; ResultSet rs = null; Project project = null; try { String sql = "select ProjectID, Title, RecordSperImage, " + "FirstYCoord, RecordHeight from Projects where ProjectID = ?"; stmt = db.getConnection().prepareStatement(sql); stmt.setInt(1, ID); rs = stmt.executeQuery(); while (rs.next()) { Project newProject = new Project(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getInt(5)); project = newProject; } } catch (SQLException e) { System.out.println("Can't execute query"); e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } catch (SQLException e) { System.out.println("Can't execute connect"); e.printStackTrace(); } } return project; }
/** update a project */ public void update(Project project) { PreparedStatement stmt = null; try { String sql = "update Projects " + "set Title = ?, RecordSperImage = ?, FirstYCoord = ?, RecordHeight = ? " + "where ProjectID = ?"; stmt = db.getConnection().prepareStatement(sql); stmt.setString(1, project.getTitle()); stmt.setInt(2, project.getRecordsPerImage()); stmt.setInt(3, project.getFirstYCoord()); stmt.setInt(4, project.getRecordHeight()); stmt.setInt(5, project.getProjectID()); if (stmt.executeUpdate() == 1) { System.out.println("Update success"); } else { System.out.println("Update fail"); } } catch (SQLException e) { System.out.println("Can't execute update"); e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException e) { System.out.println("Can't execute connect"); e.printStackTrace(); } } }
public void createNewPlayer(String player) { if (!checkConnection()) { return; } PreparedStatement preparedStatement = null; try { StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("INSERT INTO `skywars_player` "); queryBuilder.append("(`player_id`, `player_name`, `first_seen`, `last_seen`) "); queryBuilder.append("VALUES "); queryBuilder.append("(NULL, ?, NOW(), NOW());"); preparedStatement = connection.prepareStatement(queryBuilder.toString()); preparedStatement.setString(1, player); preparedStatement.executeUpdate(); } catch (final SQLException sqlException) { sqlException.printStackTrace(); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (final SQLException ignored) { } } } }
/** * Control de transacción en el procedimiento almacenado * * @param prod */ @Override public void create2(Producto prod) { Connection cn = null; try { cn = AccesoDB.getConnection(); cn.setAutoCommit(true); String query = "{call usp_crea_producto(?,?,?,?,?)}"; CallableStatement cstm = cn.prepareCall(query); cstm.registerOutParameter(1, Types.INTEGER); cstm.setInt(2, prod.getIdcat()); cstm.setString(3, prod.getNombre()); cstm.setDouble(4, prod.getPrecio()); cstm.setInt(5, prod.getStock()); cstm.executeUpdate(); prod.setIdprod(cstm.getInt(1)); cstm.close(); } catch (SQLException e) { throw new RuntimeException(e.getMessage()); } catch (Exception e) { throw new RuntimeException("No se puede crear el producto."); } finally { try { cn.close(); } catch (Exception e) { } } }
public void addValue(DeweyID deweyID, String value, int parentCID) throws IOException, Exception { // we may have problem here // maybe we should update previously inserted attributes instead of insert new one // FOR ATTrib Values (Actually they are behaved the same as text contents) // text contents are not added to element index,thier CID shouldn be Zero // elemIndex.insert(0,deweyID); // bTreeIndex.insert(deweyID,-1,value); logManager.LogManager.log(6, value); logManager.LogManager.log(6, "Value: " + deweyID.toString()); try { if (con != null) { String sqlQuery = "INSERT INTO \"OrderedByCID\" (\"CID\", \"DeweyID\" , \"Value\") VALUES (?, ? ,?);"; PreparedStatement pst = con.prepareStatement(sqlQuery); pst.setInt(1, deweyID.getCID()); pst.setString(2, deweyID.toString()); pst.setString(3, value); pst.executeUpdate(); pst.close(); } } catch (SQLException e) { System.out.println("JDBC Driver is not Configured Correctly !"); e.printStackTrace(); return; } // structSumIndex.add(-1,value,parentCID);THIS IS NOT NEEDED! // checkBufPool(); }
public void addContent(DeweyID deweyID, StringBuilder contentBuilder, int parentCID) throws IOException, Exception { String content = new String(contentBuilder); try { if (con != null) { String sqlQuery = "INSERT INTO \"OrderedByCID\" (\"CID\", \"DeweyID\" , \"Value\") VALUES (?, ? ,?);"; PreparedStatement pst = con.prepareStatement(sqlQuery); pst.setInt(1, deweyID.getCID()); pst.setString(2, deweyID.toString()); pst.setString(3, content); pst.executeUpdate(); pst.close(); } } catch (SQLException e) { System.out.println("JDBC Driver is not Configured Correctly !"); e.printStackTrace(); return; } // text contents are not added to element index,thier CID shouldn be Zero // elemIndex.insert(0,deweyID); // bTreeIndex.insert(deweyID,-2,content); // System.out.println("CID: -2"); // structSumIndex.add(-2,content,parentCID);THIS IS NOT NEEDED // checkBufPool(); }
// Yhteyden avaaminen public boolean avaaYhteys() { // Vaihe 1: tietokanta-ajurin lataaminen try { Class.forName(AJURI); } catch (ClassNotFoundException e) { System.out.println("Ajurin lataaminen ei onnistunut. Lopetetaan ohjelman suoritus."); e.printStackTrace(); return false; } // Vaihe 2: yhteyden ottaminen tietokantaan con = null; try { con = DriverManager.getConnection( PROTOKOLLA + "//" + PALVELIN + ":" + PORTTI + "/" + TIETOKANTA, KAYTTAJA, SALASANA); stmt = con.createStatement(); // Toiminta mahdollisessa virhetilanteessa } catch (SQLException e) { System.out.println("Yhteyden avaamisessa tapahtui seuraava virhe: " + e.getMessage()); e.printStackTrace(); return false; } return true; }
@Override public ArrayList<Emp> getList() { ArrayList<Emp> emps = new ArrayList<Emp>(100); if (conn == null) { System.err.println("No connect!!"); return emps; } try { Statement st = conn.createStatement(); ResultSet rs = st.executeQuery( "" + "SELECT e.id,e.lname,e.fname,e.mname,e.d_hire,e.d_fire " + "FROM DDT_EMP AS e"); while (rs.next()) { Emp emp = new Emp(); emp.setId(rs.getInt("id")); emp.setLastName(rs.getString("lname")); emp.setFirstName(rs.getString("fname")); emp.setMiddleName(rs.getString("mname")); emp.setHireDate(rs.getDate("d_hire")); emp.setFireDate(rs.getDate("d_fire")); emps.add(emp); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return emps; }
// Tulostaa resultSetin public boolean tulostaRs(ResultSet rs) { if (rs != null) { try { ResultSetMetaData rsmd = rs.getMetaData(); int columnit = rsmd.getColumnCount(); while (rs.next()) { for (int i = 1; i <= columnit; i++) { if (i > 1) System.out.print(" | "); System.out.print(rs.getString(i)); } System.out.println(""); } return true; } catch (SQLException e) { System.out.println("ResultSetin tulostuksessa tapahtui virhe: " + e.getMessage()); e.printStackTrace(); return false; } } else { System.out.println("VIRHE: tulosjoukko on tyhjä."); return false; } }
@Override public void put(Emp object) { Emp emp = object; String sql; if (emp.getId() == null) { emp.setId(DBSrv.getInstance().getNextId()); sql = "INSERT INTO DDT_EMP(lname,fname,mname,d_hire,d_fire,id) " + "VALUES(?,?,?,?,?,?)"; } else { sql = "UPDATE DDT_EMP SET " + " lname = ?, " + " fname = ?, " + " mname = ?, " + " d_hire = ?, " + " d_fire = ? " + " WHERE id = ?"; } try { PreparedStatement st = conn.prepareStatement(sql); st.setString(1, emp.getLastName()); st.setString(2, emp.getFirstName()); st.setString(3, emp.getMiddleName()); st.setDate(4, DBSrv.UtilToSQL(emp.getHireDate())); st.setDate(5, DBSrv.UtilToSQL(emp.getFireDate())); st.setInt(6, emp.getId()); st.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
public static void main(String[] args) { Connection conn = null; try { // Step 1: connect to database server Driver d = new SimpleDriver(); conn = d.connect("jdbc:simpledb://localhost", null); // Step 2: execute the query Statement stmt = conn.createStatement(); String qry = "select SName, DName " + "from DEPT, STUDENT " + "where MajorId = DId"; ResultSet rs = stmt.executeQuery(qry); // Step 3: loop through the result set System.out.println("Name\tMajor"); while (rs.next()) { String sname = rs.getString("SName"); String dname = rs.getString("DName"); System.out.println(sname + "\t" + dname); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { // Step 4: close the connection try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
/** * Close the real JDBC Connection * * @return */ public void close() { try { connection.close(); } catch (SQLException sqle) { System.err.println(sqle.getMessage()); } }
/** * Method called by the Form panel to delete existing data. * * @param persistentObject value object to delete * @return an ErrorResponse value object in case of errors, VOResponse if the operation is * successfully completed */ public Response deleteRecord(ValueObject persistentObject) throws Exception { PreparedStatement stmt = null; try { EmpVO vo = (EmpVO) persistentObject; // delete from WORKING_DAYS... stmt = conn.prepareStatement("delete from WORKING_DAYS where EMP_CODE=?"); stmt.setString(1, vo.getEmpCode()); stmt.execute(); stmt.close(); // delete from EMP... stmt = conn.prepareStatement("delete from EMP where EMP_CODE=?"); stmt.setString(1, vo.getEmpCode()); stmt.execute(); gridFrame.reloadData(); frame.getGrid().clearData(); return new VOResponse(vo); } catch (SQLException ex) { ex.printStackTrace(); return new ErrorResponse(ex.getMessage()); } finally { try { stmt.close(); conn.commit(); } catch (SQLException ex1) { } } }
/** * Updating a given appointment with new values in the persistence. * * @param appointment which shall be updated must not be null, id must not be null and must not be * changed * @return given appointment with updated values * @throws PersistenceException if there are complications with the persitance layer */ @Override public Appointment update(Appointment appointment) throws PersistenceException { LOGGER.info("Updating record in appointment table.."); try { if (appointment == null) { LOGGER.error("Update parameter (appointment) was null."); throw new PersistenceException("Appointment to be updated must not be null"); } updateStm.setDate(1, new java.sql.Date(appointment.getDatum().getTime())); updateStm.setInt(2, appointment.getSession_id()); updateStm.setInt(3, appointment.getUser_id()); updateStm.setBoolean(4, appointment.getIsTrained()); updateStm.setBoolean(5, appointment.getIsDeleted()); updateStm.setInt(6, appointment.getId()); updateStm.executeUpdate(); } catch (SQLException e) { LOGGER.error("Failed to update record in appointment table. - " + e.getMessage()); throw new PersistenceException("Failed to update record in appointment table.", e); } LOGGER.info("Record successfully updated in appointment table. " + appointment); return appointment; }
private void jButton1ActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: modelolistaDisc.clear(); ResultSet rs = null; ConectarAOBanco cd = new ConectarAOBanco(); String nome = jTextField3.getText(); nome = nome.toUpperCase(); String query = "SELECT nome FROM universidade.disciplina WHERE UPPER(nome) like'%" + nome + "%' ORDER BY nome"; cd.ConectarBanco(); rs = cd.query(query); int resultado; try { resultado = exibirDisc(rs); if (resultado == 1) { jList1.setModel(modelolistaDisc); } else { JOptionPane.showMessageDialog(this, "Disciplina não foi encontrada"); } } catch (SQLException sqlex) { sqlex.printStackTrace(); } } // GEN-LAST:event_jButton1ActionPerformed
// 创建新表 public boolean createTable(String tableName) { try { Connection conn = getConn(); if (conn != null) { StringBuilder sql = new StringBuilder("CREATE TABLE "); sql.append(tableName); sql.append(" ("); sql.append("serialno int(11) NOT NULL AUTO_INCREMENT,"); sql.append("title varchar(128) NOT NULL,"); sql.append("smalldesc varchar(512) NOT NULL,"); sql.append("smallurl varchar(256) DEFAULT NULL,"); sql.append("source varchar(32) NOT NULL,"); sql.append("releasetime bigint(20) NOT NULL,"); sql.append("content varchar(128) NOT NULL,"); sql.append("classify varchar(16) NOT NULL,"); sql.append("curl varchar(256) NOT NULL,"); sql.append("createtime varchar(14) NOT NULL,"); sql.append("PRIMARY KEY (serialno)"); sql.append(") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=gbk"); PreparedStatement stat = conn.prepareStatement(sql.toString()); stat.executeUpdate(); conn.close(); } } catch (SQLException e) { e.printStackTrace(); } return true; }
public Nutzer insert(Nutzer a) { Connection con = DBConnection.connection(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT MAX(NutzerId) AS maxid " + "FROM nutzer"); if (rs.next()) { a.setId(rs.getInt("maxid") + 1); stmt = con.createStatement(); stmt.executeUpdate( "INSERT INTO nutzer (NutzerId, Email, Vorname, Nachname, Passwort)" + "VALUES (" + a.getId() + ",'" + a.getEmail() + "','" + a.getVorname() + "','" + a.getNachname() + "','" + a.getPassword() + "')"); } } catch (SQLException e) { e.printStackTrace(); } return a; }
/** * excluir * * @param VO Usuario * @return boolean */ public static boolean excluir(Usuario usuario) { SigeDataBase db = new SigeDataBase(); try { db.getConn().setAutoCommit(false); db.prepareStatement("DELETE FROM permissao_usuario WHERE cd_usuario=?"); db.setInt(1, usuario.getCodigo()); db.executeUpdate(); db.getPreparedStatement().close(); db.prepareStatement("DELETE FROM usuarios WHERE cd_usuario=?"); db.setInt(1, usuario.getCodigo()); db.executeUpdate(); db.getConn().commit(); db.closeConnection(); return true; } catch (SQLException ex) { ex.printStackTrace(); try { db.getConn().rollback(); db.closeConnection(); } catch (SQLException ex1) { ex1.printStackTrace(); db.closeConnection(); } return false; } }
@Override public Producto readForId(int id) { Producto o = null; Connection cn = null; try { cn = AccesoDB.getConnection(); String query = "select idprod, idcat, nombre, precio, stock " + "from producto " + "where idprod = ?"; PreparedStatement pstm = cn.prepareStatement(query); pstm.setInt(1, id); ResultSet rs = pstm.executeQuery(); if (rs.next()) { o = rsToBean(rs); } rs.close(); pstm.close(); } catch (SQLException e) { throw new RuntimeException(e.getMessage()); } catch (Exception e) { throw new RuntimeException("Error en la lectura del producto."); } finally { try { cn.close(); } catch (Exception e) { } } return o; }