List of usage examples for java.sql ResultSet TYPE_SCROLL_SENSITIVE
int TYPE_SCROLL_SENSITIVE
To view the source code for java.sql ResultSet TYPE_SCROLL_SENSITIVE.
Click Source Link
ResultSet
object that is scrollable and generally sensitive to changes to the data that underlies the ResultSet
. From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java
public void setDocList(String checkpoint, String str_store_entry) { DatabaseMetaData dbm = null;/*from w ww . j a va 2s . c o m*/ Connection connection = null; logger.log(Level.FINEST, "Setting doclist " + checkpoint); logger.log(Level.FINEST, "Setting store_entry " + str_store_entry); try { connection = ds.getConnection(); connection.setAutoCommit(true); dbm = connection.getMetaData(); //logger.log(Level.FINE,"Base64 ENCODING..."); String encode_entry = new String( org.apache.commons.codec.binary.Base64.encodeBase64(str_store_entry.getBytes())); str_store_entry = encode_entry; //logger.log(Level.FINE,"Setting store_entry ENCODED " + str_store_entry); if (dbm.getDatabaseProductName().equals("MySQL")) { //get the most recent row Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String update_stmt = "select crawl_set from " + this.instance_table + " where crawl_set=(select max(crawl_set) from " + this.instance_table + ")"; logger.log(Level.FINE, "Getting lastentryp in db: " + update_stmt); ResultSet rs = statement.executeQuery(update_stmt); boolean ret_rows = rs.first(); String last_entry_in_db = null; while (ret_rows) { BigDecimal crawl_set = rs.getBigDecimal("crawl_set"); last_entry_in_db = crawl_set.toPlainString(); ret_rows = rs.next(); } logger.log(Level.FINER, "Last_Entry_in_Database " + last_entry_in_db); if (last_entry_in_db != null) { if (last_entry_in_db.startsWith(checkpoint)) { //increment if in the same set BigDecimal bd = new BigDecimal(last_entry_in_db); bd = bd.add(new BigDecimal(".00001")); logger.log(Level.INFO, "Adding to DBStore. Index Value: " + bd.toPlainString()); update_stmt = "insert into " + this.instance_table + " (crawl_set,crawl_data) values (?,COMPRESS(?))"; PreparedStatement ps = connection.prepareStatement(update_stmt); ps.setString(1, bd.toPlainString()); ps.setString(2, str_store_entry); ps.executeUpdate(); ps.close(); } else { //otherwise add the the 0th row for this set logger.log(Level.INFO, "Adding to DBStore. Index Value: " + checkpoint + ".00000"); update_stmt = "insert into " + this.instance_table + " (crawl_set,crawl_data) values (?,COMPRESS(?))"; PreparedStatement ps = connection.prepareStatement(update_stmt); ps.setString(1, checkpoint + ".00000"); ps.setString(2, str_store_entry); ps.executeUpdate(); ps.close(); } } else { logger.log(Level.INFO, "Adding to DBStore. Index Value: " + checkpoint + ".00000"); update_stmt = "insert into " + this.instance_table + " (crawl_set,crawl_data) values (?,COMPRESS(?))"; PreparedStatement ps = connection.prepareStatement(update_stmt); ps.setString(1, checkpoint + ".00000"); ps.setString(2, str_store_entry); ps.executeUpdate(); ps.close(); } rs.close(); statement.close(); connection.close(); } } catch (Exception ex) { logger.log(Level.SEVERE, "Exception initializing context Datasource " + ex); return; } }
From source file:org.apache.ambari.server.orm.DBAccessorImpl.java
@Override public void updateTable(String tableName, DBColumnInfo columnNameFrom, DBColumnInfo columnNameTo) throws SQLException { LOG.info("Executing query: UPDATE TABLE " + tableName + " SET " + columnNameTo.getName() + "=" + columnNameFrom.getName()); String statement = "SELECT * FROM " + tableName; int typeFrom = getColumnType(tableName, columnNameFrom.getName()); int typeTo = getColumnType(tableName, columnNameTo.getName()); ResultSet rs = executeSelect(statement, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); while (rs.next()) { convertUpdateData(rs, columnNameFrom, typeFrom, columnNameTo, typeTo); rs.updateRow();/*from w w w. j av a 2 s . c o m*/ } rs.close(); }
From source file:net.ymate.platform.persistence.jdbc.scaffold.JdbcScaffold.java
/** * @param dbName ???/*from w w w.j a v a 2 s.c o m*/ * @param dbUserName ?? * @param tableName ?? * @return ????? */ private TableMeta getTableMeta(String dbName, String dbUserName, String tableName) { IConnectionHolder _connHolder = null; Statement _statement = null; ResultSet _resultSet = null; Map<String, ColumnInfo> _tableFields = new LinkedHashMap<String, ColumnInfo>(); List<String> _pkFields = new LinkedList<String>(); TableMeta _meta = new TableMeta(_pkFields, _tableFields); try { _connHolder = JDBC.getConnectionHolder(); String _dbType = JDBC_SCAFFOLD_CONF.getProperty("ymp.scaffold.jbdc.db_type", "unknow"); DatabaseMetaData _dbMetaData = _connHolder.getConnection().getMetaData(); _resultSet = _dbMetaData.getPrimaryKeys(dbName, _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName, tableName); if (_resultSet == null) { _meta = null; System.err.println("Database table \"" + tableName + "\" primaryKey resultSet is null, ignored"); } else { while (_resultSet.next()) { _pkFields.add(_resultSet.getString(4).toLowerCase()); } if (_pkFields.isEmpty()) { _meta = null; System.err .println("Database table \"" + tableName + "\" does not set the primary key, ignored"); } else { _statement = _connHolder.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); _resultSet = _statement .executeQuery("select * from " + _connHolder.getDialect().wapperQuotedIdent(tableName)); ResultSetMetaData _rsMetaData = _resultSet.getMetaData(); // for (int _idx = 1; _idx <= _rsMetaData.getColumnCount(); _idx++) { // ?? ResultSet _column = _dbMetaData.getColumns(dbName, _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName, tableName, _rsMetaData.getColumnName(_idx)); if (_column.next()) { // ???? _tableFields.put(_rsMetaData.getColumnName(_idx).toLowerCase(), new ColumnInfo(_rsMetaData.getColumnName(_idx).toLowerCase(), compressType(_rsMetaData.getColumnClassName(_idx)), _rsMetaData.isAutoIncrement(_idx), _rsMetaData.isNullable(_idx), _column.getString("COLUMN_DEF"))); } } // System.err.println("TABLE_NAME: " + tableName + " ---------------->>"); System.err.println("COLUMN_NAME\tPK\tCOLUMN_TYPE\tIS_AUTOINCREMENT\tIS_NULLABLE\tCOLUMN_DEF"); for (ColumnInfo _cInfo : _tableFields.values()) { System.err .println(_cInfo.getColumnName() + "\t" + _pkFields.contains(_cInfo.getColumnName()) + "\t" + _cInfo.getColumnType() + "\t" + _cInfo.isAutoIncrement() + "\t" + _cInfo.getNullable() + "\t" + _cInfo.getDefaultValue()); } } } } catch (Throwable e) { if (e instanceof Error) { throw (Error) e; } throw new Error(RuntimeUtils.unwrapThrow(e)); } finally { _connHolder.release(); _statement = null; _resultSet = null; } return _meta; }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testDataTypes() throws SQLException { conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); Statement stat = conn.createStatement(); PreparedStatement prep;/* w w w .j av a 2s . c om*/ ResultSet rs; trace("Create tables"); stat.execute("CREATE TABLE T_INT(ID INT PRIMARY KEY,VALUE INT)"); stat.execute("CREATE TABLE T_VARCHAR(ID INT PRIMARY KEY,VALUE VARCHAR(255))"); stat.execute("CREATE TABLE T_DECIMAL_0(ID INT PRIMARY KEY,VALUE DECIMAL(30,0))"); stat.execute("CREATE TABLE T_DECIMAL_10(ID INT PRIMARY KEY,VALUE DECIMAL(20,10))"); stat.execute("CREATE TABLE T_DATETIME(ID INT PRIMARY KEY,VALUE DATETIME)"); prep = conn.prepareStatement("INSERT INTO T_INT VALUES(?,?)", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); prep.setInt(1, 1); prep.setInt(2, 0); prep.executeUpdate(); prep.setInt(1, 2); prep.setInt(2, -1); prep.executeUpdate(); prep.setInt(1, 3); prep.setInt(2, 3); prep.executeUpdate(); prep.setInt(1, 4); prep.setNull(2, Types.INTEGER); prep.executeUpdate(); prep.setInt(1, 5); prep.setBigDecimal(2, new BigDecimal("0")); prep.executeUpdate(); prep.setInt(1, 6); prep.setString(2, "-1"); prep.executeUpdate(); prep.setInt(1, 7); prep.setObject(2, new Integer(3)); prep.executeUpdate(); prep.setObject(1, "8"); // should throw an exception prep.setObject(2, null); // some databases don't allow calling setObject with null (no data type) prep.executeUpdate(); prep.setInt(1, 9); prep.setObject(2, -4, Types.VARCHAR); prep.executeUpdate(); prep.setInt(1, 10); prep.setObject(2, "5", Types.INTEGER); prep.executeUpdate(); prep.setInt(1, 11); prep.setObject(2, null, Types.INTEGER); prep.executeUpdate(); prep.setInt(1, 12); prep.setBoolean(2, true); prep.executeUpdate(); prep.setInt(1, 13); prep.setBoolean(2, false); prep.executeUpdate(); prep.setInt(1, 14); prep.setByte(2, (byte) -20); prep.executeUpdate(); prep.setInt(1, 15); prep.setByte(2, (byte) 100); prep.executeUpdate(); prep.setInt(1, 16); prep.setShort(2, (short) 30000); prep.executeUpdate(); prep.setInt(1, 17); prep.setShort(2, (short) (-30000)); prep.executeUpdate(); prep.setInt(1, 18); prep.setLong(2, Integer.MAX_VALUE); prep.executeUpdate(); prep.setInt(1, 19); prep.setLong(2, Integer.MIN_VALUE); prep.executeUpdate(); assertTrue(stat.execute("SELECT * FROM T_INT ORDER BY ID")); rs = stat.getResultSet(); assertResultSetOrdered(rs, new String[][] { { "1", "0" }, { "2", "-1" }, { "3", "3" }, { "4", null }, { "5", "0" }, { "6", "-1" }, { "7", "3" }, { "8", null }, { "9", "-4" }, { "10", "5" }, { "11", null }, { "12", "1" }, { "13", "0" }, { "14", "-20" }, { "15", "100" }, { "16", "30000" }, { "17", "-30000" }, { "18", "" + Integer.MAX_VALUE }, { "19", "" + Integer.MIN_VALUE }, }); prep = conn.prepareStatement("INSERT INTO T_DECIMAL_0 VALUES(?,?)"); prep.setInt(1, 1); prep.setLong(2, Long.MAX_VALUE); prep.executeUpdate(); prep.setInt(1, 2); prep.setLong(2, Long.MIN_VALUE); prep.executeUpdate(); prep.setInt(1, 3); prep.setFloat(2, 10); prep.executeUpdate(); prep.setInt(1, 4); prep.setFloat(2, -20); prep.executeUpdate(); prep.setInt(1, 5); prep.setFloat(2, 30); prep.executeUpdate(); prep.setInt(1, 6); prep.setFloat(2, -40); prep.executeUpdate(); rs = stat.executeQuery("SELECT VALUE FROM T_DECIMAL_0 ORDER BY ID"); checkBigDecimal(rs, new String[] { "" + Long.MAX_VALUE, "" + Long.MIN_VALUE, "10", "-20", "30", "-40" }); }
From source file:org.giswater.dao.MainDao.java
public static ResultSet getResultset(Connection connection, String sql, boolean showError) { return getResultset(connection, sql, showError, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); }
From source file:annis.dao.SpringAnnisDao.java
@Transactional(readOnly = true) @Override//w ww .j a v a 2 s. com public void matrix(final QueryData queryData, final boolean outputCsv, final OutputStream out) { prepareTransaction(queryData); getJdbcTemplate().execute(new ConnectionCallback<Boolean>() { @Override public Boolean doInConnection(Connection con) throws SQLException, DataAccessException { try (Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(matrixSqlGenerator.toSql(queryData));) { AnnotatedMatchIterator itMatches = new AnnotatedMatchIterator(rs, matrixSqlGenerator.getSpanExtractor()); // write the header to the output stream PrintWriter w = new PrintWriter(new OutputStreamWriter(out, "UTF-8")); if (outputCsv) { SortedMap<Integer, SortedSet<String>> columnsByNodePos = CSVHelper .exportCSVHeader(itMatches, w); w.flush(); // go back to the beginning and print the actual data itMatches.reset(); CSVHelper.exportCSVData(itMatches, columnsByNodePos, w); } else { SortedMap<Integer, SortedSet<String>> columnsByNodePos = WekaHelper .exportArffHeader(itMatches, w); w.flush(); // go back to the beginning and print the actual data itMatches.reset(); WekaHelper.exportArffData(itMatches, columnsByNodePos, w); } w.flush(); } catch (UnsupportedEncodingException ex) { log.error("Your system is not able to handle UTF-8 but ANNIS really needs this charset", ex); } return true; } }); }
From source file:recite18th.controller.Controller.java
public void print(String action) { /** thanks to http://www.java2s.com/Code/Java/PDF-RTF/DemonstratesthecreatingPDFinportraitlandscape.htm * QUICK FIX : do landscape//from w w w. j av a 2 s . c om */ response.setContentType("application/pdf"); // Code 1 if (action.equals("download")) { response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "attachment; filename=\"" + "Report " + controllerName + ".pdf\""); } Document document = new Document(PageSize.A1.rotate()); try { PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // Code 2 document.open(); // various fonts BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false); BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false); BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false); BaseFont bf_symbol = BaseFont.createFont(BaseFont.SYMBOL, "Cp1252", false); String headerImage = Config.base_path + "images/report-logo.gif"; Image imghead = Image.getInstance(headerImage); imghead.setAbsolutePosition(0, 0); PdfContentByte cbhead = writer.getDirectContent(); PdfTemplate tpLogo = cbhead.createTemplate(600, 300); tpLogo.addImage(imghead); PdfTemplate tpTitle = cbhead.createTemplate(1100, 300); String txtHeader = "BADAN KEPEGAWAIAN DAERAH PEMERINTAH DAERAH";//Config.application_title; tpTitle.beginText(); tpTitle.setFontAndSize(bf_times, 36); tpTitle.showText(txtHeader); tpTitle.endText(); PdfTemplate tpTitle2 = cbhead.createTemplate(900, 300); String txtHeader2 = " KABUPATEN BANTUL YOGYAKARTA"; tpTitle2.beginText(); tpTitle2.setFontAndSize(bf_times, 36); tpTitle2.showText(txtHeader2); tpTitle2.endText(); PdfTemplate tpAlamat = cbhead.createTemplate(1000, 400); tpAlamat.beginText(); tpAlamat.setFontAndSize(bf_times, 24); tpAlamat.showText( "Alamat : Jln. R. W. Monginsidi No. 01 Kompleks Parasamya Bantul, Telp. (0274) 367509"); tpAlamat.endText(); DateFormat df = new SimpleDateFormat("dd MMM yyyy"); java.util.Date dt = new java.util.Date(); PdfTemplate tp3 = cbhead.createTemplate(600, 300); tp3.beginText(); tp3.setFontAndSize(bf_times, 16); tp3.showText("Tanggal : " + df.format(dt)); tp3.endText(); cbhead.addTemplate(tpLogo, 800, 1500);//logo cbhead.addTemplate(tpTitle, 1000, 1580); cbhead.addTemplate(tpTitle2, 1000, 1540); cbhead.addTemplate(tpAlamat, 1000, 1500);//alamat cbhead.addTemplate(tp3, 270, 1500);//tanggal HeaderFooter header = new HeaderFooter(new Phrase(cbhead + "", new Font(bf_helv)), false); header.setAlignment(Element.ALIGN_CENTER); document.setHeader(header); //PdfContentByte cb = writer.getDirectContent(); Paragraph par = new Paragraph( "\n\n\n\n\n\n\nLAPORAN DATA SELURUH " + controllerName.toUpperCase() + "\n"); par.getFont().setStyle(Font.BOLD); par.getFont().setSize(18); par.setAlignment("center"); document.add(par); document.add(new Paragraph("\n\n")); // get data initSqlViewDataPerPage(); if (sqlViewDataPerPageForReport == null) { sqlViewDataPerPageForReport = sqlViewDataPerPage; } PreparedStatement pstmt = Db.getCon().prepareStatement(sqlViewDataPerPageForReport, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet resultSet = pstmt.executeQuery(); ResultSetMetaData metaColumn = resultSet.getMetaData(); int nColoumn = metaColumn.getColumnCount(); // thanks to set cell width http://www.jexp.ru/index.php/Java/PDF_RTF/Table_Cell_Size#Setting_Cell_Widths if (nColoumn > 0) { Model model = initModel(); String tableName = model.getTableName(); // create table header // float[] widths = {1, 4}; PdfPTable table;// = new PdfPTable(nColoumn); PdfPCell cell = new PdfPCell(new Paragraph("Daftar " + controllerName)); Hashtable hashModel = TableCustomization.getTable(model.getTableName()); int ncolumnHeader = nColoumn + 1; // +1 because of row. number if (hashModel != null) { ncolumnHeader = Integer.parseInt("" + hashModel.get("columnCount")) + 1; } table = new PdfPTable(ncolumnHeader); cell.setColspan(ncolumnHeader); cell.setHorizontalAlignment(Element.ALIGN_CENTER); Paragraph p2 = new Paragraph("No."); p2.getFont().setSize(20); PdfPCell cellColNo = new PdfPCell(p2); cellColNo.setNoWrap(true); cellColNo.setMinimumHeight(50); cellColNo.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cellColNo); if (hashModel != null) { Enumeration k = hashModel.keys(); while (k.hasMoreElements()) { String key = (String) k.nextElement(); if (key.equals("columnCount")) { continue; } PdfPCell cellCol = new PdfPCell(new Paragraph(hashModel.get(key) + "")); cellCol.setNoWrap(true); cellCol.setMinimumHeight(50); cellCol.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cellCol); } } else { for (int i = 1; i < ncolumnHeader; i++) { System.out.println("DATA = " + metaColumn.getColumnName(i)); Paragraph p1 = new Paragraph(metaColumn.getColumnName(i) + ""); p1.getFont().setSize(20); PdfPCell cellCol = new PdfPCell(p1); cellCol.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cellCol); } } //iterate all columns : table data resultSet.beforeFirst(); int row = 1; while (resultSet.next()) { System.out.println(row); Paragraph p3 = new Paragraph(row + ""); p3.getFont().setSize(20); cell = new PdfPCell(p3); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); if (hashModel != null) {//skip dulu u/ kasus ga pny class kustomasi table Enumeration k = hashModel.keys(); while (k.hasMoreElements()) { String key = (String) k.nextElement(); if (key.equals("columnCount")) { continue; } table.addCell(resultSet.getObject(key) + ""); } } else { for (int i = 1; i < ncolumnHeader; i++) { System.out.println("DATA = " + metaColumn.getColumnName(i)); Paragraph p1 = new Paragraph(resultSet.getObject(metaColumn.getColumnName(i)) + ""); p1.getFont().setSize(18); PdfPCell cellCol = new PdfPCell(p1); cellCol.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cellCol); } } row++; } document.add(table); document.add(new Paragraph("\n\n")); par = new Paragraph("Mengetahui"); par.setAlignment("center"); document.add(par); par = new Paragraph("Kepada Badan Kepegawaian"); par.setAlignment("center"); document.add(par); par = new Paragraph("\n\n\n"); document.add(par); par = new Paragraph("Drs. Maman Permana"); par.setAlignment("center"); document.add(par); par = new Paragraph("Nip: 197802042006041013"); par.setAlignment("center"); document.add(par); } document.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.alibaba.wasp.jdbc.JdbcConnection.java
private void checkTypeConcurrency(int resultSetType, int resultSetConcurrency) { switch (resultSetType) { case ResultSet.TYPE_FORWARD_ONLY: case ResultSet.TYPE_SCROLL_INSENSITIVE: case ResultSet.TYPE_SCROLL_SENSITIVE: break;/*w w w. ja va 2 s .co m*/ default: throw JdbcException.getInvalidValueException("resultSetType", resultSetType); } switch (resultSetConcurrency) { case ResultSet.CONCUR_READ_ONLY: case ResultSet.CONCUR_UPDATABLE: break; default: throw JdbcException.getInvalidValueException("resultSetConcurrency", resultSetConcurrency); } }
From source file:uk.ac.kcl.texthunter.core.AnnotationEditor.java
private void outputGATEXML() throws SQLException { // TODO add your handling code here: if (XMLradioButton.isSelected()) { Utils.checkGateInit(this.gateHomeDir, GlobalParameters.debugOn); Corpus allDocs;// ww w . ja va 2 s.c om if (gateXMLjRadioButton.isSelected()) { expressModeRadioButton.setEnabled(true); changeMode(); tab2SQLEditorPane.setText(getAnnotationsXMLOutputSQL); if (withKeyAnnotationsRadioButton.isSelected() & outputFullDocumentsRadioButton.isSelected()) { allDocs = mkCorpusFromDB2(getAnnotationsXMLOutputSQL, true, true, -1); } else if (noKeyAnnotationsRadioButton.isSelected() & outputFullDocumentsRadioButton.isSelected()) { allDocs = mkCorpusFromDB2(getAnnotationsXMLOutputSQL, false, true, -1); } else if (withKeyAnnotationsRadioButton.isSelected() & outputContextOnlyRadioButton.isSelected()) { allDocs = mkCorpusFromDB2(getAnnotationsXMLOutputSQL, true, false, -1); } else { allDocs = mkCorpusFromDB2(getAnnotationsXMLOutputSQL, false, false, -1); } int i = 1; //index for doc count for (gate.Document doc : allDocs) { try { gate.corpora.DocumentStaxUtils.writeDocument(doc, new File(outputFileChooser.getCurrentDirectory() + File.separator + i + "_" + doc.getName())); } catch (XMLStreamException | IOException ex) { infoBox(ex.getMessage(), "error"); Logger.getLogger(AnnotationEditor.class.getName()).log(Level.SEVERE, null, ex); } i++; } } else if (knowtatorXMLjRadioButton.isSelected()) { allDocs = getContextStringsFromDB(tab2SQLEditorPane.getText()); File knowtatorAnnotsDir = new File(outputFileChooser.getCurrentDirectory() + "knowtatorAnnots"); int n = 0; if (knowtatorAnnotsDir.exists()) { Object[] options = { "OK", "Cancel" }; n = JOptionPane.showOptionDialog(null, "An annotation folder already exists. Do you want to delete it?\n" + projectLocation, "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); } if (n == 0) { for (int i = 0; i <= 5; i++) { try { Thread.sleep(500); FileUtils.deleteDirectory(knowtatorAnnotsDir); } catch (IOException ex) { System.out.println("Attempting deletion " + i); } catch (InterruptedException ex) { Logger.getLogger(AnnotationEditor.class.getName()).log(Level.SEVERE, null, ex); } } if (knowtatorAnnotsDir.exists()) { try { FileUtils.deleteDirectory(knowtatorAnnotsDir); } catch (IOException ex) { Logger.getLogger(AnnotationEditor.class.getName()).log(Level.SEVERE, null, ex); } } } knowtatorAnnotsDir.mkdir(); int instanceSuffix = 1; for (gate.Document doc : allDocs) { try (BufferedWriter bw = new BufferedWriter(new FileWriter( new File(outputFileChooser.getCurrentDirectory() + File.separator + doc.getName())))) { bw.write(doc.getContent().toString()); org.jdom.Document xmlOutDoc = new org.jdom.Document(); instanceSuffix++; Utils.buildKnowtatorXMLDocumentFromGATEXML(xmlOutDoc, doc, instanceSuffix, targetTableName); XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat()); xmlOut.output(xmlOutDoc, new FileOutputStream( new File(knowtatorAnnotsDir, doc.getName() + ".knowtator.xml"))); } catch (IOException ex) { Logger.getLogger(AnnotationEditor.class.getName()).log(Level.SEVERE, null, ex); } } } System.out.println("XML output complete"); } else { try { Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = statement.executeQuery(SQLCommands.getInstance().getResultsForCSV()); BufferedWriter bw = new BufferedWriter(new FileWriter( outputFileChooser.getCurrentDirectory() + File.separator + GlobalParameters.OUTPUTTSV)); ResultSetMetaData rsmd = rs.getMetaData(); int colCount = rsmd.getColumnCount(); for (int i = 1; i <= colCount - 1; i++) { bw.write(rsmd.getColumnName(i) + "\t"); } bw.write(rsmd.getColumnName(colCount) + System.lineSeparator()); bw.flush(); int flushIndex = 0; int index = 0; while (rs.next()) { for (int i = 1; i <= colCount - 1; i++) { bw.write(rs.getString(i) + "\t"); } bw.write(rs.getString(colCount) + System.lineSeparator()); index++; if (index > flushIndex + 50) { bw.flush(); flushIndex = index; } } bw.close(); } catch (SQLException | IOException ex) { Logger.getLogger(AnnotationEditor.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.lewa.crazychapter11.MainActivity.java
private void sqlCon() { try {//from www. j a v a 2 s.c om Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { e.printStackTrace(); } try { // String url = "jdbc:mysql://192.168.142.128:3306/mysql?user=zzfeihua&password=12345&useUnicode=true&characterEncoding=UTF-8";// ?? String url = "jdbc:mysql://10.0.4.170:3306/lewa?user=root&password=lewa&useUnicode=true&characterEncoding=UTF-8";// ?? Connection conn = (Connection) DriverManager.getConnection(url); // ? Statement stmt = (Statement) conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql = "select * from user";// user? ResultSet rs = stmt.executeQuery(sql);// StringBuilder str = new StringBuilder(); while (rs.next()) { str.append(rs.getString(1) + "\n"); } mSetText(str.toString()); rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } }