public void put(ByteArray key, Versioned<byte[]> value) throws PersistenceFailureException { StoreUtils.assertValidKey(key); boolean doCommit = false; Connection conn = null; PreparedStatement insert = null; PreparedStatement select = null; ResultSet results = null; String insertSql = "insert into " + name + " (key_, version_, value_) values (?, ?, ?)"; String selectSql = "select key_, version_ from " + name + " where key_ = ?"; try { conn = datasource.getConnection(); conn.setAutoCommit(false); // check for superior versions select = conn.prepareStatement(selectSql); select.setBytes(1, key.get()); results = select.executeQuery(); while (results.next()) { byte[] thisKey = results.getBytes("key_"); VectorClock version = new VectorClock(results.getBytes("version_")); Occured occured = value.getVersion().compare(version); if (occured == Occured.BEFORE) throw new ObsoleteVersionException( "Attempt to put version " + value.getVersion() + " which is superceeded by " + version + "."); else if (occured == Occured.AFTER) delete(conn, thisKey, version.toBytes()); } // Okay, cool, now put the value insert = conn.prepareStatement(insertSql); insert.setBytes(1, key.get()); VectorClock clock = (VectorClock) value.getVersion(); insert.setBytes(2, clock.toBytes()); insert.setBytes(3, value.getValue()); insert.executeUpdate(); doCommit = true; } catch (SQLException e) { if (e.getErrorCode() == MYSQL_ERR_DUP_KEY || e.getErrorCode() == MYSQL_ERR_DUP_ENTRY) { throw new ObsoleteVersionException("Key or value already used."); } else { throw new PersistenceFailureException("Fix me!", e); } } finally { if (conn != null) { try { if (doCommit) conn.commit(); else conn.rollback(); } catch (SQLException e) { } } tryClose(results); tryClose(insert); tryClose(select); tryClose(conn); } }
public boolean createConnection() { try { if (validateConnection() && validateConnectiontoDBMS()) return true; validateConnectiontoDBMS(); MyConnection = DriverManager.getConnection(ConnectionString, Username, Password); return true; } catch (SQLException e) { JOptionPane.showMessageDialog( null, e.getErrorCode() + " : " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); if (e.getErrorCode() == 1045) JOptionPane.showMessageDialog( null, "The Username & Password you've entered is invalid.\nSet the Username & Password for MySQL Database Management System correctly.", "Invalid Username Password Combination", JOptionPane.ERROR_MESSAGE); if (e.getErrorCode() == 1049) JOptionPane.showMessageDialog( null, "Required database is missing.\nMost probably, It has been deleted recently.\nTo overcome this problem please, restart the application.", "Database Missing", JOptionPane.ERROR_MESSAGE); if (e.getErrorCode() == 0) JOptionPane.showMessageDialog( null, "Can't connect to MySQL server on 'localhost'.\n Ensure MySQL Database Management System is running on your computer.", "Connection Interruption", JOptionPane.ERROR_MESSAGE); return false; } }
@Test public void testRowTimestampDisabled() throws SQLException { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); try { stmt.execute( "CREATE TABLE DEMO(k VARCHAR, v VARCHAR, d DATE NOT NULL, CONSTRAINT PK PRIMARY KEY(k,d ROW_TIMESTAMP)) TRANSACTIONAL=true"); fail(); } catch (SQLException e) { assertEquals( SQLExceptionCode.CANNOT_CREATE_TXN_TABLE_WITH_ROW_TIMESTAMP.getErrorCode(), e.getErrorCode()); } stmt.execute( "CREATE TABLE DEMO(k VARCHAR, v VARCHAR, d DATE NOT NULL, CONSTRAINT PK PRIMARY KEY(k,d ROW_TIMESTAMP))"); try { stmt.execute("ALTER TABLE DEMO SET TRANSACTIONAL=true"); fail(); } catch (SQLException e) { assertEquals( SQLExceptionCode.CANNOT_ALTER_TO_BE_TXN_WITH_ROW_TIMESTAMP.getErrorCode(), e.getErrorCode()); } } }
public void test_batchInsert_unique_constraint_OriginalException() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); { Member member = new Member(); member.setMemberName("testName1"); member.setMemberAccount("testAccount1"); member.setMemberStatusCode_Formalized(); // 正式会員 memberList.add(member); } { Member member = new Member(); member.setMemberName("testName2"); member.setMemberAccount("testAccount2"); member.setMemberStatusCode_Formalized(); // 正式会員 memberList.add(member); } // ## Act & Assert ## memberBhv.batchInsert(memberList); try { memberBhv.batchInsert(memberList); fail(); } catch (EntityAlreadyExistsException e) { SQLException cause = e.getSQLException(); log(e.getMessage()); log("/* * * * * * * * * * * * * * * * *"); log("SQLState=" + cause.getSQLState() + ", ErrorCode=" + cause.getErrorCode()); log("* * * * * * * * * */"); assertEquals(MY_SQLSTATE, cause.getSQLState()); assertEquals(MY_ERRORCODE, cause.getErrorCode()); } }
public void test_batchUpdateNonstrict_unique_constraint_OriginalException() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); { Member member = memberBhv.selectByPKValueWithDeletedCheck(memberIdTwo); member.setMemberAccount("AAA"); memberList.add(member); } { Member member = memberBhv.selectByPKValueWithDeletedCheck(memberIdThree); member.setMemberAccount("Pixy"); memberList.add(member); } // ## Act & Assert ## try { memberBhv.batchUpdateNonstrict(memberList); fail(); } catch (EntityAlreadyExistsException e) { SQLException cause = e.getSQLException(); log(e.getMessage()); log("/* * * * * * * * * * * * * * * * *"); log("SQLState=" + cause.getSQLState() + ", ErrorCode=" + cause.getErrorCode()); log("* * * * * * * * * */"); assertEquals(MY_SQLSTATE, cause.getSQLState()); assertEquals(MY_ERRORCODE, cause.getErrorCode()); } }
private void btnUpdateActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnUpdateActionPerformed try { String newTypeName = tfUpdateName.getText(); String oldTypeName = lstTypes.getSelectedValue().toString(); PreparedStatement st = con.prepareStatement(Queries.UPDATE_SITE_TYPE); st.setString(1, newTypeName); st.setString(2, oldTypeName); st.executeUpdate(); fillTypes(); } catch (SQLException e) { if (e.getErrorCode() == 547) { JOptionPane.showInternalMessageDialog( this, "This type is already in use!", "Bummer!", JOptionPane.ERROR_MESSAGE); System.err.println( "Error code: " + e.getErrorCode() + "\nError Message: " + e.getMessage()); } else { System.err.println( "Error code: " + e.getErrorCode() + "\nError Message: " + e.getMessage()); } } } // GEN-LAST:event_btnUpdateActionPerformed
/** DeleteUser */ @WebMethod(operationName = "deleteUser", action = "deleteUser") @Oneway public void deleteUser(@WebParam(name = "login") String login) { Connection con = null; Statement st = null; ResultSet rs = null; try { con = DriverManager.getConnection( PostgresConfig.url, PostgresConfig.user, PostgresConfig.password); st = con.createStatement(); //////////////////////////////////////////////////////////////////////////////// st.execute("DELETE FROM users WHERE login='******';"); System.out.println("Polaczono"); //////////////////////////////////////////////////////////////////////////////// } catch (SQLException e) { System.out.println("Blad polaczenia"); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); if (con != null) con.close(); } catch (SQLException ex) { System.out.println("Blad zamykania polaczenia"); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); } } }
/** Logout */ @WebMethod(operationName = "logout", action = "logout") @Oneway public void logout(@WebParam(name = "sessionId") String sessionId) { Connection con = null; Statement st = null; ResultSet rs = null; try { con = DriverManager.getConnection( PostgresConfig.url, PostgresConfig.user, PostgresConfig.password); st = con.createStatement(); //////////////////////////////////////////////////////////////////////////////// st.executeUpdate("UPDATE users SET session_id=NULL WHERE session_id='" + sessionId + "';"); System.out.println("Polaczono"); //////////////////////////////////////////////////////////////////////////////// } catch (SQLException e) { System.out.println("Blad polaczenia"); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); if (con != null) con.close(); } catch (SQLException ex) { System.out.println("Blad zamykania polaczenia"); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); } } }
@Test public void testCreateTableToBeTransactional() throws Exception { Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); String ddl = "CREATE TABLE TEST_TRANSACTIONAL_TABLE (k varchar primary key) transactional=true"; conn.createStatement().execute(ddl); PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class); PTable table = pconn.getTable(new PTableKey(null, "TEST_TRANSACTIONAL_TABLE")); HTableInterface htable = pconn.getQueryServices().getTable(Bytes.toBytes("TEST_TRANSACTIONAL_TABLE")); assertTrue(table.isTransactional()); assertTrue( htable .getTableDescriptor() .getCoprocessors() .contains(TransactionProcessor.class.getName())); try { ddl = "ALTER TABLE TEST_TRANSACTIONAL_TABLE SET transactional=false"; conn.createStatement().execute(ddl); fail(); } catch (SQLException e) { assertEquals(SQLExceptionCode.TX_MAY_NOT_SWITCH_TO_NON_TX.getErrorCode(), e.getErrorCode()); } HBaseAdmin admin = pconn.getQueryServices().getAdmin(); HTableDescriptor desc = new HTableDescriptor(TableName.valueOf("TXN_TEST_EXISTING")); desc.addFamily(new HColumnDescriptor(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES)); admin.createTable(desc); ddl = "CREATE TABLE TXN_TEST_EXISTING (k varchar primary key) transactional=true"; conn.createStatement().execute(ddl); assertEquals( Boolean.TRUE.toString(), admin .getTableDescriptor(TableName.valueOf("TXN_TEST_EXISTING")) .getValue(TxConstants.READ_NON_TX_DATA)); // Should be ok, as HBase metadata should match existing metadata. ddl = "CREATE TABLE IF NOT EXISTS TEST_TRANSACTIONAL_TABLE (k varchar primary key)"; try { conn.createStatement().execute(ddl); fail(); } catch (SQLException e) { assertEquals(SQLExceptionCode.TX_MAY_NOT_SWITCH_TO_NON_TX.getErrorCode(), e.getErrorCode()); } ddl += " transactional=true"; conn.createStatement().execute(ddl); table = pconn.getTable(new PTableKey(null, "TEST_TRANSACTIONAL_TABLE")); htable = pconn.getQueryServices().getTable(Bytes.toBytes("TEST_TRANSACTIONAL_TABLE")); assertTrue(table.isTransactional()); assertTrue( htable .getTableDescriptor() .getCoprocessors() .contains(TransactionProcessor.class.getName())); }
// ------------------------------------------------------------ // Helper methods // ------------------------------------------------------------ private void compareResults(String sql, Object[][] rows, int errorCode) throws SQLException { ResultSet rs = null; try { rs = stmt.executeQuery(sql); assertTrue("Statement <" + sql + "> \nexpecting error code: " + errorCode, (0 == errorCode)); } catch (SQLException sqlx) { if (sqlx.getErrorCode() != errorCode) { sqlx.printStackTrace(); } assertTrue( "Statement <" + sql + "> \nthrows wrong error code: " + sqlx.getErrorCode() + " expecting error code: " + errorCode, (sqlx.getErrorCode() == errorCode)); return; } int rowCount = 0; int colCount = rows.length > 0 ? rows[0].length : 0; while (rs.next()) { assertTrue("Statement <" + sql + "> \nreturned too many rows.", (rowCount < rows.length)); Object[] columns = rows[rowCount]; for (int col = 1, i = 0; i < colCount; i++, col++) { Object result = null; Object expected = columns[i]; if (expected == null) { result = rs.getString(col); result = rs.wasNull() ? null : result; } else if (expected instanceof String) { result = rs.getString(col); } else if (expected instanceof Double) { result = new Double(rs.getString(col)); } else if (expected instanceof Integer) { result = new Integer(rs.getInt(col)); } assertEquals("Statement <" + sql + "> \nreturned wrong value.", columns[i], result); } rowCount++; } assertEquals("Statement <" + sql + "> \nreturned wrong number of rows.", rows.length, rowCount); }
@WebMethod(operationName = "updateUser", action = "updateUser") public void updateUser( @WebParam(name = "sessionId") String sessionId, @WebParam(name = "login") String login, @WebParam(name = "firstName") String firstName, @WebParam(name = "lastName") String lastName, @WebParam(name = "phoneNumber") String phoneNumber, @WebParam(name = "mail") String mail) { Connection con = null; Statement st = null; ResultSet rs = null; try { con = DriverManager.getConnection( PostgresConfig.url, PostgresConfig.user, PostgresConfig.password); // if(!checkSessionId(login, sessionId, con)) // return; st = con.createStatement(); //////////////////////////////////////////////////////////////////////////////// st.execute( "UPDATE users SET " + "imie=\'" + firstName + "\', " + "nazwisko=\'" + lastName + "\', " + "telefon=\'" + phoneNumber + "\', " + "mail=\'" + mail + "\' " + " WHERE login=\'" + login + "\'"); //////////////////////////////////////////////////////////////////////////////// } catch (SQLException e) { System.out.println("Blad polaczenia"); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); if (con != null) con.close(); } catch (SQLException ex) { System.out.println("Blad zamykania polaczenia"); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); } } }
@Test public void testAlteringMultiTenancyForTableWithViewsNotAllowed() throws Exception { Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(nextTimestamp())); String multiTenantTable = "BASE_MULTI_TENANT_SWITCH"; String globalTable = "GLOBAL_TABLE_SWITCH"; // create the two base tables try (Connection conn = DriverManager.getConnection(getUrl(), props)) { String ddl = "CREATE TABLE " + multiTenantTable + " (TENANT_ID VARCHAR NOT NULL, PK1 VARCHAR NOT NULL, V1 VARCHAR, V2 VARCHAR, V3 VARCHAR CONSTRAINT NAME_PK PRIMARY KEY(TENANT_ID, PK1)) MULTI_TENANT = true "; conn.createStatement().execute(ddl); ddl = "CREATE TABLE " + globalTable + " (TENANT_ID VARCHAR NOT NULL, PK1 VARCHAR NOT NULL, V1 VARCHAR, V2 VARCHAR, V3 VARCHAR CONSTRAINT NAME_PK PRIMARY KEY(TENANT_ID, PK1)) "; conn.createStatement().execute(ddl); } props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(nextTimestamp())); props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, "tenant1"); // create view on multi-tenant table try (Connection tenantConn = DriverManager.getConnection(getUrl(), props)) { String viewName = "tenantview"; String viewDDL = "CREATE VIEW " + viewName + " AS SELECT * FROM " + multiTenantTable; tenantConn.createStatement().execute(viewDDL); } props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(nextTimestamp())); // create view on global table try (Connection conn = DriverManager.getConnection(getUrl(), props)) { String viewName = "globalView"; conn.createStatement() .execute("CREATE VIEW " + viewName + " AS SELECT * FROM " + globalTable); } props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(nextTimestamp())); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { try { conn.createStatement() .execute("ALTER TABLE " + globalTable + " SET MULTI_TENANT = " + true); fail(); } catch (SQLException e) { assertEquals(SQLExceptionCode.CANNOT_MUTATE_TABLE.getErrorCode(), e.getErrorCode()); } try { conn.createStatement() .execute("ALTER TABLE " + multiTenantTable + " SET MULTI_TENANT = " + false); fail(); } catch (SQLException e) { assertEquals(SQLExceptionCode.CANNOT_MUTATE_TABLE.getErrorCode(), e.getErrorCode()); } } }
/** * Retrieves different specified items from a special IRDI from de_class. * * @param Statement: A Statement object for sending SQL statements to the database. * @param tableNames: A collection of column tables * @param irdi: The official unique identifier. * @throws implementation_exception */ public Dictionary<String, String> GetSelectedItemsFromClass( Statement statement, String[] tableNames, String irdi) throws implementation_exception { ResultSet resultSet = null; try { Dictionary<String, String> resultBuffer = new Hashtable<String, String>(); String internalId = GetInternalId(statement, irdi); if (internalId.contentEquals("null") || internalId.length() == 0) { String expression = String.format("select * from de_class where IRDI = '%s'", irdi); ; resultSet = statement.executeQuery(expression); } else { String expression = String.format("select * from table (pkgProperty.gettable( %s ))", internalId); ; resultSet = statement.executeQuery(expression); } while (resultSet.next()) { for (int index = 0; index < tableNames.length; index++) { if (resultSet.getString(tableNames[index]) == null) { resultBuffer.put(tableNames[index], ""); } else { resultBuffer.put(tableNames[index], resultSet.getString(tableNames[index])); } } } return resultBuffer; } catch (SQLException exception) { WebServiceLogger.Log( "DatabaseAccess.java", "GetInternalIrdi", String.format("Get selected item failed: %s", exception.getMessage())); throw new implementation_exception( String.format("Close connection failed: %s", exception.getMessage()), exception.getErrorCode()); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException exception) { WebServiceLogger.Log( "DatabaseAccess.java", "GetInternalIrdi", String.format("Close connection failed: %s", exception.getMessage())); throw new implementation_exception( String.format("Close connection failed: %s", exception.getMessage()), exception.getErrorCode()); } } } }
/** GetUser */ @WebMethod(operationName = "getUser", action = "getUser") public User getUser( @WebParam(name = "sessionId") String sessionId, @WebParam(name = "login") String login) { Connection con = null; Statement st = null; ResultSet rs = null; User foundUser = null; try { con = DriverManager.getConnection( PostgresConfig.url, PostgresConfig.user, PostgresConfig.password); // if(!checkSessionId(login, sessionId, con)) // return null; st = con.createStatement(); //////////////////////////////////////////////////////////////////////////////// rs = st.executeQuery("SELECT * FROM users WHERE login=\'" + login + "\'"); while (rs.next()) { User user = new User(); user.setFirstName(rs.getString("imie")); user.setLastName(rs.getString("nazwisko")); user.setLogin(rs.getString("login")); user.setMail(rs.getString("mail")); user.setPhoneNumber(rs.getString("telefon")); foundUser = user; break; } System.out.println("Polaczono"); //////////////////////////////////////////////////////////////////////////////// } catch (SQLException e) { System.out.println("Blad polaczenia"); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); if (con != null) con.close(); } catch (SQLException ex) { System.out.println("Blad zamykania polaczenia"); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); } } return foundUser; }
/** {@inheritDoc} */ @Override public List<PretDTO> getAll(Connexion connexion, String sortByPropertyName) throws DAOException, InvalidHibernateSessionException, InvalidSortByPropertyException { if (connexion == null) { throw new InvalidHibernateSessionException("La connexion ne peut être null"); } if (sortByPropertyName == null) { throw new InvalidSortByPropertyException("La propriété ne peut être null"); } List<PretDTO> prets = Collections.<PretDTO>emptyList(); try (PreparedStatement statementGetAllLivres = (connexion.getConnection().prepareStatement(PretDAO.GET_ALL_REQUEST))) { try (ResultSet resultSet = statementGetAllLivres.executeQuery()) { PretDTO pretDTO = null; if (resultSet.next()) { prets = new ArrayList<>(); do { pretDTO = new PretDTO(); pretDTO.setIdPret(resultSet.getString(1)); MembreDTO membre = new MembreDTO(); membre.setIdMembre(resultSet.getString(2)); LivreDTO livre = new LivreDTO(); livre.setIdLivre(resultSet.getString(3)); pretDTO.setMembreDTO(membre); pretDTO.setLivreDTO(livre); pretDTO.setDatePret(resultSet.getTimestamp(4)); pretDTO.setDateRetour(resultSet.getTimestamp(5)); prets.add(pretDTO); } while (resultSet.next()); } return prets; } catch (SQLException sqlException) { throw new DAOException( Integer.toString(sqlException.getErrorCode()) + " " + sqlException.getMessage(), sqlException); } } catch (SQLException sqlException) { throw new DAOException( Integer.toString(sqlException.getErrorCode()) + " " + sqlException.getMessage(), sqlException); } }
/** Login user. Returns sessionId */ @WebMethod(operationName = "login", action = "login") public String login( @WebParam(name = "login") String login, @WebParam(name = "md5password") String md5password) { // String result = null; String result = "FAILED"; Connection con = null; Statement st = null; ResultSet rs = null; try { con = DriverManager.getConnection( PostgresConfig.url, PostgresConfig.user, PostgresConfig.password); st = con.createStatement(); //////////////////////////////////////////////////////////////////////////////// // TODO: sprawdzanie poprawnosci loginu String query = "SELECT * FROM users WHERE login='******';"; System.out.println(query); rs = st.executeQuery(query); if (rs.next()) { if (rs.getString("md5password").equals(md5password)) { String sessionId = Util.md5(login + md5password + (new Date())); st.executeUpdate( "UPDATE users SET session_id='" + sessionId + "' WHERE login='******';"); result = sessionId; } } System.out.println("Polaczono"); //////////////////////////////////////////////////////////////////////////////// } catch (SQLException e) { System.out.println("Blad polaczenia"); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); result = null; } finally { try { if (rs != null) rs.close(); if (st != null) st.close(); if (con != null) con.close(); } catch (SQLException ex) { System.out.println("Blad zamykania polaczenia"); System.out.println(ex.getMessage()); System.out.println(ex.getErrorCode()); } } return result; }
public String addToDB() { if (wordExists()) { return String.valueOf( ChatColor.RED + "The word " + ChatColor.GOLD + word.getName() + ChatColor.RED + " already exists!"); } else { try { Connection con = null; if (sqltype.equals(SQLType.SQLite)) con = sqlite.getConnection(); if (sqltype.equals(SQLType.MySQL)) con = mysql.getConnection(); PreparedStatement p = con.prepareStatement(Query.INSERT_INTO.value()); p.setString(1, word.getName()); p.setString(2, word.getGroup()); p.addBatch(); con.setAutoCommit(false); p.executeBatch(); con.setAutoCommit(true); return String.valueOf( ChatColor.GREEN + "Word " + ChatColor.GOLD + word.getName() + ChatColor.GREEN + " has been successfully added!"); } catch (SQLException e) { plugin.sendErr( "Error while adding the word '" + word.getName() + "' to the database. Error message: " + e.getMessage() + " ERROR CODE: " + e.getErrorCode()); e.printStackTrace(); return String.valueOf( ChatColor.RED + "Error adding the word '" + ChatColor.GOLD + word.getName() + ChatColor.RED + "' Please check the console for more info."); } catch (Exception e) { plugin.sendErr( "Unknown error while adding the word " + word.getName() + " to the database. Stacktrace:"); e.printStackTrace(); return String.valueOf( ChatColor.RED + "Error adding the word '" + ChatColor.GOLD + word.getName() + ChatColor.RED + "' Please check the console for more info."); } } }
public String getWordGroup() { ResultSet rs = null; if (sqltype.equals(SQLType.SQLite)) rs = sqlite.query(Query.SELECT_GROUPNAME.value() + " name='" + word.getName() + "'"); if (sqltype.equals(SQLType.MySQL)) rs = mysql.query(Query.SELECT_GROUPNAME.value() + "name='" + word.getName() + "'"); try { String s = null; while (rs.next()) { s = rs.getString(1); } return s; } catch (SQLException e) { plugin.sendErr( "SQLException while getting the word " + word.getName() + "'s group from the database. Error message: " + e.getMessage() + " ERROR CODE: " + e.getErrorCode()); e.printStackTrace(); return null; } }
/** * retourne la liste des catégories définies dans la bd * * @param Utilisateur * @return Vector<Categorie> * @throws CategorieException * @throws ExceptionConnexion */ public static Vector<Categorie> getCategorie(Utilisateur user) throws CategorieException, ExceptionConnexion { Vector<Categorie> res = new Vector<Categorie>(); String requete; Statement stmt; ResultSet rs; Connection conn = BDConnexion.getConnexion(user.getLogin(), user.getmdp()); requete = "select nomc, prix from LesCategories order by nomc"; try { stmt = conn.createStatement(); rs = stmt.executeQuery(requete); while (rs.next()) { res.addElement(new Categorie(rs.getString(1), rs.getFloat(2))); } } catch (SQLException e) { throw new CategorieException( " Problème dans l'interrogation des catégories.." + "Code Oracle " + e.getErrorCode() + "Message " + e.getMessage()); } BDConnexion.FermerTout(conn, stmt, rs); return res; }
/** * * * <PRE> * Desc : Retrieve SQL * </PRE> * * @param Connection * @param RetrieveModel * @return RetrieveModel */ public RetrieveModel retrieve(Connection con, RetrieveModel retrieve) throws StoreException { PreparedStatement pstmt = null; ResultSet rset = null; try { pstmt = con.prepareStatement(makeSql(retrieve)); int index = 1; pstmt.setString(index++, retrieve.getString("pay_yymm")); pstmt.setString(index++, retrieve.getString("pay_times")); pstmt.setString(index++, retrieve.getString("entp_code")); rset = pstmt.executeQuery(); retrieve.put("RESULT", makeSheet(rset)); } catch (SQLException se) { log.error( "[AccountPaymentRegSvc.retrieve() SQLException : ERR-" + se.getErrorCode() + ":" + se); throw new StoreException(se.getMessage()); } catch (Exception e) { log.error("[AccountPaymentRegSvc.retrieve() Exception : ERR-" + e.getMessage()); throw new StoreException(e.getMessage()); } finally { DBUtils.freeConnection(null, pstmt, rset); } return retrieve; }
/** * 例外チェーンをたどって原因となった{@link SQLException#getErrorCode() ベンダー固有の例外コード}を返します。 * * <p>例外チェーンに{@link SQLException SQL例外}が存在しない場合や、例外コードが設定されていない場合は <code>null</code>を返します。 * * @param t 例外 * @return 原因となった{@link SQLException#getErrorCode() ベンダー固有の例外コード} */ protected Integer getErrorCode(Throwable t) { SQLException cause = getCauseSQLException(t); if (cause != null) { return cause.getErrorCode(); } return null; }
// TODO public int insertCert(ApkBean apk) { int ret = -1; for (CertBean cert : apk.certs) { try { PreparedStatement pstmt = null; String marketUpdateQuery = "INSERT INTO cert " + "(issuer,certhash,certBrief)" + " VALUES(?, ?,?) "; pstmt = (PreparedStatement) conn.prepareStatement(marketUpdateQuery); pstmt.setString( 1, ((X509Certificate) cert.certificate).getIssuerX500Principal().toString()); pstmt.setString(2, cert.certificateHash); pstmt.setString(3, apk.certInfo()); pstmt.executeUpdate(); ret = 0; } catch (SQLException e) { if (e.getErrorCode() == 1062) { return 0; } e.printStackTrace(); ret = -2; } } return ret; }
private void sendError(Throwable t) { try { SQLException e = DbException.convert(t).getSQLException(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String trace = writer.toString(); String message; String sql; if (e instanceof JdbcSQLException) { JdbcSQLException j = (JdbcSQLException) e; message = j.getOriginalMessage(); sql = j.getSQL(); } else { message = e.getMessage(); sql = null; } transfer .writeInt(SessionRemote.STATUS_ERROR) .writeString(e.getSQLState()) .writeString(message) .writeString(sql) .writeInt(e.getErrorCode()) .writeString(trace) .flush(); } catch (Exception e2) { if (!transfer.isClosed()) { server.traceError(e2); } // if writing the error does not work, close the connection stop = true; } }
/** * Metodo faz a conexao com o banco de dados, com os dados que recebeu da camada de negocio, * executa a alteracao e fecha a conexao com o banco * * @param corrida * @return * @throws exception_RegistroJaExisteException */ public int altera(vo.vo_Corrida corrida) throws exception_RegistroJaExisteException, ClassNotFoundException, SQLException { conn = this.getConnection(); int alterou; if (corrida != null) { alterou = corrida.getEtapa(); PreparedStatement pstmt; try { pstmt = conn.prepareStatement( "update gridlargada set cod_pista = ?, posicao = ? where cod_prova = ? and cod_piloto = ?"); pstmt.setInt(1, corrida.getCodPista()); pstmt.setInt(2, corrida.getPosicao().getPosicao()); pstmt.setInt(3, corrida.getEtapa()); pstmt.setInt(4, corrida.getCodPiloto()); pstmt.execute(); conn.commit(); pstmt.close(); } catch (SQLException e) { if (e.getErrorCode() == -104) { throw new exception_RegistroJaExisteException("Piloto"); } else { e.printStackTrace(); } } } else { alterou = -1; } return alterou; }
/** * Metodo faz a conexao com o banco de dados, pega os dados que recebeu da camada de negocio, faz * a insercao com esses dados e fecha a conexao. * * @param corrida * @return * @throws exception_RegistroJaExisteException */ public int insere(vo.vo_Corrida corrida) throws exception_RegistroJaExisteException, ClassNotFoundException, SQLException { conn = this.getConnection(); int inseriu; if (corrida != null) { inseriu = corrida.getEtapa(); PreparedStatement pstmt; try { pstmt = conn.prepareStatement( "insert into gridlargada (cod_prova, cod_piloto, cod_pista, posicao) values (?, ?, ?, ?)"); pstmt.setInt(1, corrida.getEtapa()); pstmt.setInt(2, corrida.getCodPiloto()); pstmt.setInt(3, corrida.getCodPista()); pstmt.setInt(4, corrida.getPosicao().getPosicao()); pstmt.execute(); conn.commit(); pstmt.close(); } catch (SQLException e) { if (e.getErrorCode() == -104) { throw new exception_RegistroJaExisteException("Piloto"); } else { e.printStackTrace(); } } } else { inseriu = -1; } return inseriu; }
private List<UsersFriends> FindBy(String SQL) { List<UsersFriends> usersFriendsList = new ArrayList<UsersFriends>(); try { this.dbHandler.openConnection(); Statement statement = this.dbHandler.getConnection().createStatement(); ResultSet result = statement.executeQuery(SQL); while (result.next()) { usersFriendsList.add( new UsersFriends( result.getInt("id"), result.getInt("id_user"), result.getInt("id_friend"))); } // else System.out.println("Записи с данными параметрами не существует"); } catch (SQLException ex) { System.out.println("SQLException caught"); System.out.println("---"); while (ex != null) { System.out.println("Message : " + ex.getMessage()); System.out.println("SQLState : " + ex.getSQLState()); System.out.println("ErrorCode : " + ex.getErrorCode()); System.out.println("---"); ex = ex.getNextException(); } } catch (Exception ex) { System.out.println("Other Error in Main."); } return usersFriendsList; }
@Override public void Insert(UsersFriends usersFriends) { // SQL // INSERT INTO UsersFriends (VkID_User, VkID_Friend) VALUES (usersFriends.getVkIDUser(), // usersFriends.getVkIDFriend()); String SQL = ""; try { this.dbHandler.openConnection(); Statement statement = this.dbHandler.getConnection().createStatement(); SQL = "INSERT INTO UsersFriends (VkID_User, VkID_Friend) VALUES (\"" + usersFriends.getVkIDUser() + "\",\"" + usersFriends.getVkIDFriend() + "\")"; statement.executeUpdate(SQL); } catch (SQLException ex) { System.out.println("SQLException caught"); System.out.println("---"); while (ex != null) { System.out.println("Message : " + ex.getMessage()); System.out.println("SQLState : " + ex.getSQLState()); System.out.println("ErrorCode : " + ex.getErrorCode()); System.out.println("---"); ex = ex.getNextException(); } } catch (Exception ex) { System.out.println("Other Error in Main."); } }
public synchronized void updateThumbnail( String name, long modified, int type, DLNAMediaInfo media) { Connection conn = null; PreparedStatement ps = null; try { conn = getConnection(); ps = conn.prepareStatement("UPDATE FILES SET THUMB = ? WHERE FILENAME = ? AND MODIFIED = ?"); ps.setString(2, name); ps.setTimestamp(3, new Timestamp(modified)); if (media != null) { ps.setBytes(1, media.getThumb()); } else { ps.setNull(1, Types.BINARY); } ps.executeUpdate(); } catch (SQLException se) { if (se.getErrorCode() == 23001) { LOGGER.debug( "Duplicate key while inserting this entry: " + name + " into the database: " + se.getMessage()); } else { LOGGER.error(null, se); } } finally { close(ps); close(conn); } }
int doTransaction(Xid xid, int mode, int command) throws XAException { int returnVal = -1; try { try { T4CTTIOtxen otxen = physicalConn.otxen; byte xidxid[] = null; byte gtrid[] = xid.getGlobalTransactionId(); byte bqual[] = xid.getBranchQualifier(); int gtrid_l = 0; int bqual_l = 0; if (gtrid != null && bqual != null) { gtrid_l = Math.min(gtrid.length, 64); bqual_l = Math.min(bqual.length, 64); xidxid = new byte[128]; System.arraycopy(gtrid, 0, xidxid, 0, gtrid_l); System.arraycopy(bqual, 0, xidxid, gtrid_l, bqual_l); } byte txctx[] = context; physicalConn.sendPiggyBackedMessages(); otxen.marshal(mode, txctx, xidxid, xid.getFormatId(), gtrid_l, bqual_l, timeout, command); returnVal = otxen.receive(errorNumber); } catch (IOException ioe) { DatabaseError.throwSqlException(ioe); } } catch (SQLException s) { errorNumber[0] = s.getErrorCode(); } if (errorNumber[0] == 0) { throw new XAException(-6); } if (returnVal == -1) { returnVal = errorNumber[0]; } return returnVal; }
/** * Metodo faz a conexao com o banco de dados, faz a exclusao com os dados que recebeu da camada de * negocio e fecha a conexao com o banco. * * @param corrida * @return * @throws exception_RegistroJaExisteException */ public int exclui(vo.vo_Corrida corrida) throws exception_RegistroJaExisteException, ClassNotFoundException, SQLException { conn = this.getConnection(); int excluiu; if (corrida != null) { excluiu = corrida.getEtapa(); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("delete from gridlargada where cod_prova = ? and cod_piloto = ?"); pstmt.setInt(1, corrida.getEtapa()); pstmt.setInt(2, corrida.getCodPiloto()); pstmt.execute(); conn.commit(); pstmt.close(); } catch (SQLException e) { if (e.getErrorCode() == -104) { throw new exception_RegistroJaExisteException("Piloto"); } else { e.printStackTrace(); } } } else { excluiu = -1; } return excluiu; }