List of usage examples for java.sql Statement execute
boolean execute(String sql) throws SQLException;
From source file:org.copperengine.core.test.persistent.BasePersistentWorkflowTest.java
void cleanDB(DataSource ds) throws Exception { new RetryingTransaction<Void>(ds) { @Override/*w ww.j av a 2 s . c o m*/ protected Void execute() throws Exception { Statement stmt = createStatement(getConnection()); stmt.execute("DELETE FROM COP_AUDIT_TRAIL_EVENT"); stmt.close(); stmt = createStatement(getConnection()); stmt.execute("DELETE FROM COP_WAIT"); stmt.close(); stmt = createStatement(getConnection()); stmt.execute("DELETE FROM COP_RESPONSE"); stmt.close(); stmt = createStatement(getConnection()); stmt.execute("DELETE FROM COP_QUEUE"); stmt.close(); stmt = createStatement(getConnection()); stmt.execute("DELETE FROM COP_WORKFLOW_INSTANCE"); stmt.close(); stmt = createStatement(getConnection()); stmt.execute("DELETE FROM COP_WORKFLOW_INSTANCE_ERROR"); stmt.close(); stmt = createStatement(getConnection()); stmt.execute("DELETE FROM COP_LOCK"); stmt.close(); return null; } }.run(); }
From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java
/** * Test the {@code Set} object in Cassandra. *//*from w w w . j ava 2 s . c o m*/ @Test public void testObjectSet() throws Exception { Statement stmt = con.createStatement(); // Create the target Column family String createCF = "CREATE COLUMNFAMILY t65 (key text PRIMARY KEY," + "int1 int, " + "int2 int, " + "intset set<int> " + ") ;"; stmt.execute(createCF); stmt.close(); con.close(); // open it up again to see the new CF con = DriverManager .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS)); Statement statement = con.createStatement(); String insert = "INSERT INTO t65 (key, int1,int2,intset) VALUES ('key1',1,100,{10,20,30,40});"; statement.executeUpdate(insert); ResultSet result = statement.executeQuery("SELECT intset FROM t65 where key = 'key1';"); // read the Set of Integer back out again Object rsObject = result.getObject(1); assertNotNull("Object Should Exist", rsObject); assertTrue("Object Should be Set", (rsObject instanceof Set)); int sum = 0; // sum up the set - it should be 100 for (Object rsEntry : ((Set) rsObject).toArray()) { assertTrue("Entry should be Integer", (rsEntry instanceof Integer)); sum += ((Integer) rsEntry).intValue(); } assertEquals("Total Should be 100", 100, sum); //System.out.println(resultToDisplay(result,65, "with set = {10,20,30,40}")); String update = "UPDATE t65 SET intset=? WHERE key=?;"; PreparedStatement pstatement = con.prepareStatement(update); Set<Integer> mySet = new HashSet<Integer>(); pstatement.setObject(1, mySet, Types.OTHER); pstatement.setString(2, "key1"); pstatement.executeUpdate(); result = statement.executeQuery("SELECT * FROM t65;"); System.out.println(resultToDisplay(result, 65, " with set = <empty>")); }
From source file:com.transcend.rds.worker.CreateDBInstanceReadReplicaActionWorker.java
/** * createDBInstanceReadReplica ******************************************* * Creates a read replica for a named master database instance All of the * characteristics of the read replica default to the characteristics of the * the master instance with the exception of InstanceClass, * AvailabilityZone,Port and AutoMinorVersionUpgrade that can be provided by * the user. Request: SourceDBInstanceIdentifier (R) DBInstanceIdentifier * for the read replica (R) DBInstanceClass AvailabilityZone Port * AutoMinorVersionUpgrade Response: Full details of new DBInstance created * Exceptions: DBIInstanceAlreadyExists DBInstanceNotFound * DBParameterGroupNotFound DBSecurityGroupNotFound InstanceQuotaExceeded * InsufficientDBInstanceCapacity InvalidDBInstanceState * StorageQuotaExceeded Processing 1. Confirm that source DBInstance exists * 2. Determined that requested DBInstance replica doesn't already exist for * that user 3. Confirm quotas have not been exceeded (instance, * availabilityZone, storage) 4. Validate and insert the DBInstance and * associated records 5. Call the instance manager to provision the read * replica 6. Return response giving details of newly created replica * instance including end point./*from ww w. j a v a 2 s. c o m*/ */ @Override protected CreateDBInstanceReadReplicaActionResultMessage doWork0( CreateDBInstanceReadReplicaActionRequestMessage req, ServiceRequestContext context) throws Exception { final Session sess = HibernateUtil.newSession(); DBInstance dbInst = null; try { sess.beginTransaction(); final AccountBean ac = context.getAccountBean(); final long userId = ac.getId(); final boolean autoUpgrade = req.getAutoMinorVersionUpgrade(); String avZone = req.getAvailabilityZone(); String DBInstanceClass = req.getDbInstanceClass(); final String DBInstanceId = req.getDbInstanceIdentifier(); int port = req.getPort(); final String sourceDBInstanceId = req.getSourceDBInstanceIdentifier(); if (sourceDBInstanceId == null || "".equals(sourceDBInstanceId)) { throw QueryFaults.MissingParameter( "SourceDBInstanceIdentifier must be supplied for CreateDBInstanceReadReplica request."); } if (DBInstanceId == null || "".equals(DBInstanceId)) { throw QueryFaults.MissingParameter( "DBInstanceIdentifier must be supplied for CreateDBInstanceReadReplica request."); } final RdsDbinstance source = InstanceEntity.selectDBInstance(sess, sourceDBInstanceId, userId); if (source == null || "".equals(source)) { throw RDSQueryFaults.DBInstanceNotFound(sourceDBInstanceId + " does not exist."); } if (!source.getDbinstanceStatus().equals(RDSUtilities.STATUS_AVAILABLE)) { throw RDSQueryFaults.InvalidDBInstanceState(); } if (port == -1) { logger.debug("request did not include port; port value is set with " + source.getPort() + " from the source DBInstance."); port = source.getPort(); } if (DBInstanceClass == null || "".equals(DBInstanceClass)) { logger.debug("request did not include DBInstanceClass; DBInstanceClass value is set with " + source.getDbinstanceClass() + " from the source DBInstance."); DBInstanceClass = source.getDbinstanceClass(); } if (avZone == null || "".equals(avZone)) { logger.debug( "AvailabilityZone is not included in the request; it is set to the default zone of the account: " + ac.getDefZone()); avZone = ac.getDefZone(); } logger.debug("Preparing the request for CreateDBInstance"); final CreateDBInstanceActionRequestMessage.Builder createDBInstanceReq = CreateDBInstanceActionRequestMessage .newBuilder(); createDBInstanceReq.setAllocatedStorage(source.getAllocatedStorage()); createDBInstanceReq.setAutoMinorVersionUpgrade(autoUpgrade); createDBInstanceReq.setAvailabilityZone(avZone); createDBInstanceReq.setBackupRetentionPeriod(source.getBackupRetentionPeriod()); createDBInstanceReq.setDbInstanceClass(DBInstanceClass); createDBInstanceReq.setDbInstanceIdentifier(DBInstanceId); createDBInstanceReq.setDbParameterGroupName(source.getDbParameterGroup()); final List<RdsDbsecurityGroup> dbSecGrps = source.getSecurityGroups(); final LinkedList<String> dbSecGrpNames = new LinkedList<String>(); for (final RdsDbsecurityGroup secGrp : dbSecGrps) { dbSecGrpNames.add(secGrp.getDbsecurityGroupName()); } createDBInstanceReq.addAllDbSecurityGroups(dbSecGrpNames); createDBInstanceReq.setEngine(source.getEngine()); createDBInstanceReq.setEngineVersion(source.getEngineVersion()); createDBInstanceReq.setLicenseModel(source.getLicenseModel()); createDBInstanceReq.setMasterUsername(source.getMasterUsername()); createDBInstanceReq.setMasterUserPassword(source.getMasterUserPassword()); createDBInstanceReq.setMultiAZ(false); createDBInstanceReq.setPort(port); createDBInstanceReq.setPreferredBackupWindow(source.getPreferredBackupWindow()); createDBInstanceReq.setPreferredMaintenanceWindow(source.getPreferredMaintenanceWindow()); logger.debug("Request: " + createDBInstanceReq.toString()); logger.debug("Calling CreateDBInstance..."); final CreateDBInstanceActionWorker createAction = new CreateDBInstanceActionWorker(); dbInst = createAction.createDBInstance(createDBInstanceReq.buildPartial(), context, true); logger.debug("Adding another authorization to the underlying ec2 security group"); final String internal = "rds-" + ac.getId() + "-" + source.getDbinstanceId() + "-" + source.getPort(); final List<RdsDbsecurityGroup> secGrps = SecurityGroupEntity.selectAllSecurityGroups(sess, internal, ac.getId(), null, 0); if (secGrps.size() != 1) { throw RDSQueryFaults.InternalFailure(); } final String rds_host = Appctx.getBean("internalServiceIp"); final String RdsServerCidrip = rds_host + "/32"; final RdsDbsecurityGroup masterSecGrp = secGrps.get(0); final List<RdsIPRangeBean> ips = masterSecGrp.getIPRange(sess); boolean authorized = false; for (final RdsIPRangeBean ip : ips) { if (ip.getCidrip().equals(RdsServerCidrip)) { authorized = true; logger.debug("Authorization already exists for " + RdsServerCidrip); } } final int port0 = source.getPort(); if (!authorized) { logger.debug("Authorizing ingress for " + RdsServerCidrip + " to access the source DBInstance."); final CallStruct callEc2SecGrp = new CallStruct(); callEc2SecGrp.setAc(AccountUtil.toAccount(ac)); callEc2SecGrp.setCtx(new TemplateContext(null)); callEc2SecGrp.setName(internal); callEc2SecGrp.setStackId("rds." + ac.getId() + "." + sourceDBInstanceId); final Map<String, Object> props = new HashMap<String, Object>(); props.put(Constants.AVAILABILITYZONE, ac.getDefZone()); props.put(Constants.GROUPNAME, internal); props.put(Constants.CIDRIP, RdsServerCidrip); props.put(Constants.SOURCESECURITYGROUPNAME, null); // SourceSecurityGroupOwnerId is not required props.put(Constants.SOURCESECURITYGROUPOWNERID, null); // hardcoded values below props.put(Constants.FROMPORT, port0); props.put(Constants.TOPORT, port0); props.put(Constants.IPPROTOCOL, Constants.DEFAULT_RDS_PROTOCOL); callEc2SecGrp.setProperties(props); callEc2SecGrp.setType(SecurityGroupIngress.TYPE); final SecurityGroupIngress provider0 = new SecurityGroupIngress(); try { provider0.create(callEc2SecGrp); } catch (final AmazonServiceException e) { logger.debug(e.getMessage()); } catch (final AmazonClientException e) { logger.debug(e.getMessage()); } final RdsIPRangeBean newAuth = new RdsIPRangeBean(masterSecGrp.getId(), RdsServerCidrip); ips.add(newAuth); sess.save(newAuth); } // modify the source DBInstance's status and commit the transaction source.setDbinstanceStatus(RDSUtilities.STATUS_MODIFYING); source.getReplicas().add(DBInstanceId); sess.save(source); sess.getTransaction().commit(); final Connection master = getConnection("root", source.getMasterUserPassword(), source.getEngine().toLowerCase(), source.getAddress(), source.getPort()); logger.debug("Checking to see if the source DBInstance has RDS replication user already..."); final String checkPermission = "SELECT User from mysql.user"; final Statement check = master.createStatement(); final ResultSet existingGrant = check.executeQuery(checkPermission); boolean exist = false; while (existingGrant.next()) { final String user = existingGrant.getString("User"); logger.debug("User: " + user); if (user.equals(RDS_Constants.RDS_REPLICATION_USER)) { exist = true; } } // create a new user and grant replication privilege if (!exist) { logger.debug("Replicaion user for RDS does not exist; creating a replication user..."); final String grantPermission = "GRANT REPLICATION SLAVE ON *.* TO \'" + RDS_Constants.RDS_REPLICATION_USER + "\'@\'%\' IDENTIFIED BY \'" + RDS_Constants.RDS_REPLICATION_PASSWORD + "\'"; final PreparedStatement grant = master.prepareStatement(grantPermission); grant.execute(); } logger.debug("Flushing tables with read lock on the source DBInstance..."); final String flushTables = "FLUSH TABLES WITH READ LOCK"; final Statement flushTablesAndLock = master.createStatement(); flushTablesAndLock.execute(flushTables); logger.debug("Getting the master status"); final String getMasterStatus = "SHOW MASTER STATUS"; final Statement queryMasterStatus = master.createStatement(); final ResultSet masterStatus = queryMasterStatus.executeQuery(getMasterStatus); String masterFile = null; int position = -1; while (masterStatus.next()) { masterFile = masterStatus.getString("File"); position = masterStatus.getInt("Position"); // ignore Binlog_Do_DB and Binlog_Ignore_DB for now } logger.debug("Master file is " + masterFile + " and the position is set at " + position); if (masterFile == null || position == -1) { RDSQueryFaults.InternalFailure("Master status could not be retrieved from the source DBInstance."); } logger.debug("Unlocking the tables..."); final String unlockTables = "UNLOCK TABLES"; final Statement unlock = master.createStatement(); unlock.execute(unlockTables); logger.debug("Successfully unlocked the tables."); logger.debug("Close the connection to the source DBInstance."); master.close(); logger.debug("Updating the databag to run the replication_server.rb recipe"); final String task = "mysqldump"; final String target = "?"; final String databagName = "rds-" + ac.getId() + "-" + source.getDbinstanceId(); final String replication_item = "{\"Task\":\"" + task + "\", " + "\"TargetHostname\":\"" + target + "\"}"; ChefUtil.createDatabagItem(databagName, "Replication"); ChefUtil.putDatabagItem(databagName, "Replication", replication_item); logger.debug( "Starting a new thread to wait for read replica to spin up while returning the response message."); final String DBInstanceId0 = DBInstanceId; final String sourceDBInstanceId0 = sourceDBInstanceId; final String avZone0 = avZone; final String masterFile0 = masterFile; final int position0 = position; final int port1 = port; final Executable r = new ExecutorHelper.Executable() { @Override public void run() { HibernateUtil.withNewSession(new HibernateUtil.Operation<Object>() { @Override public Object ex(final Session s, final Object... as) throws Exception { replicationHelper(s, ac, DBInstanceId0, sourceDBInstanceId0, avZone0, port0, port1, masterFile0, position0); return null; } }); } }; ExecutorHelper.execute(r); } catch (final ErrorResponse rde) { sess.getTransaction().rollback(); throw rde; } catch (final Exception e) { e.printStackTrace(); sess.getTransaction().rollback(); final String msg = "CreateDBInstanceReadReplica: Class: " + e.getClass() + "Msg:" + e.getMessage(); logger.error(msg); throw RDSQueryFaults.InternalFailure(); } finally { sess.close(); } CreateDBInstanceReadReplicaActionResultMessage.Builder resp = CreateDBInstanceReadReplicaActionResultMessage .newBuilder(); resp.setDbInstance(dbInst); return resp.buildPartial(); }
From source file:localdomain.localhost.CasInitializer.java
@Override public void afterPropertiesSet() throws Exception { System.err.println(/*from w ww. j av a2 s . com*/ "##############################################################################################"); System.err.println( "##############################################################################################"); System.err.println( "# #"); System.err.println( "# CLOUDBEES JASIG CAS SSO SERVER CLICKSTART #"); System.err.println( "# #"); System.err.println( "# See documentation at https://github.com/CloudBees-community/jasig-cas-clickstart/wiki #"); System.err.println( "# #"); System.err.println( "##############################################################################################"); System.err.println( "##############################################################################################"); try { authenticationHandler = applicationContext.getBean(SearchModeSearchDatabaseAuthenticationHandler.class); } catch (NoSuchBeanDefinitionException e) { String msg = "No Spring bean of type " + SearchModeSearchDatabaseAuthenticationHandler.class + " found, initializer can not run"; logger.warn(msg); throw new IllegalStateException(msg, e); } dataSource = (DataSource) ReflectionUtils.getField(dataSourceField, authenticationHandler); fieldUser = (String) ReflectionUtils.getField(fieldUserField, authenticationHandler); fieldPassword = (String) ReflectionUtils.getField(fieldPasswordField, authenticationHandler); tableUsers = (String) ReflectionUtils.getField(tableUsersField, authenticationHandler); passwordEncoder = (PasswordEncoder) ReflectionUtils.getField(passwordEncoderField, authenticationHandler); final Connection cnn = dataSource.getConnection(); Statement stmt = null; ResultSet rst = null; try { logger.info("Create table " + tableUsers + " if not exist"); stmt = cnn.createStatement(); String createTableDdl = "CREATE TABLE IF NOT EXISTS `" + tableUsers + "` (" + " `" + fieldUser + "` varchar(255) DEFAULT NULL,\n" + " `" + fieldPassword + "` varchar(255) DEFAULT NULL,\n" + " PRIMARY KEY (`" + fieldUser + "`)\n" + ")"; stmt.execute(createTableDdl); closeQuietly(stmt); logger.info("Validate table columns"); stmt = cnn.createStatement(); String sqlCheckDatabaseTable = "select `" + fieldUser + "`,`" + fieldPassword + "`" + " from `" + tableUsers + "` where 0=1"; try { stmt.execute(sqlCheckDatabaseTable); } catch (SQLException e) { throw new IllegalStateException("Invalid table structure:" + sqlCheckDatabaseTable, e); } closeQuietly(stmt); stmt = cnn.createStatement(); String sqlCountUsers = "select count(*) from `" + tableUsers + "`"; rst = stmt.executeQuery(sqlCountUsers); rst.next(); int usersCount = rst.getInt(1); closeQuietly(stmt, rst); if (usersCount == 0) { insertUser("demo", "mode", cnn); } if (!cnn.getAutoCommit()) { cnn.commit(); } logger.info("CAS CLICKSTART INITIALIZED"); } finally { closeQuietly(cnn, stmt, rst); } }
From source file:com.nextep.designer.sqlgen.mysql.impl.MySqlCapturer.java
@Override public Collection<IBasicTable> getTables(ICaptureContext context, IProgressMonitor m) { final Map<String, IBasicColumn> columnsMap = new HashMap<String, IBasicColumn>(); final Map<String, IKeyConstraint> keysMap = new HashMap<String, IKeyConstraint>(); Connection conn = (Connection) context.getConnectionObject(); final IProgressMonitor monitor = new CustomProgressMonitor(m, 100, true); Statement stmt = null; try {/* www . j a v a 2 s . c om*/ stmt = conn.createStatement(); stmt.execute("flush tables"); //$NON-NLS-1$ } catch (SQLException e) { LOGGER.error("Unable to flush tables : " + e.getMessage(), e); //$NON-NLS-1$ } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { LOGGER.error("Unable to close statement : " + e.getMessage(), e); //$NON-NLS-1$ } } } try { // Creating statement to retrieve tables final DatabaseMetaData md = conn.getMetaData(); final Map<String, IBasicTable> tablesMap = buildTablesMap(conn, md, context, monitor); monitor.worked(1); // Building columns monitor.subTask(MySQLMessages.getString("capturer.mysql.retrievingColumns")); //$NON-NLS-1$ Map<String, IBasicColumn> localColumnsMap = buildColumnsMap(conn, md, context, monitor, tablesMap); columnsMap.putAll(localColumnsMap); monitor.worked(1); // Temporary storing columns into a map, hashed by // table_name.column_name for (String tabName : tablesMap.keySet()) { IBasicTable t = tablesMap.get(tabName); // Building unique keys monitor.subTask(MessageFormat.format(MySQLMessages.getString("capturer.mysql.retrievingPKs"), //$NON-NLS-1$ tabName)); Map<String, IKeyConstraint> localKeysMap = buildUniqueKeyMap(md, monitor, t, columnsMap); keysMap.putAll(localKeysMap); } // We iterate foreign keys in a specific loop to make sure all // unique keys are here monitor.worked(1); monitor.subTask(MySQLMessages.getString("capturer.mysql.retrievingFKs")); //$NON-NLS-1$ for (String tabName : tablesMap.keySet()) { monitor.worked(1); IBasicTable t = tablesMap.get(tabName); fillForeignKeys(md, monitor, t, keysMap, columnsMap); } monitor.worked(1); return tablesMap.values(); } catch (SQLException e) { LOGGER.warn(MessageFormat.format(MySQLMessages.getString("capturer.mysql.fetchTablesError"), //$NON-NLS-1$ e.getMessage()), e); } return Collections.emptyList(); }
From source file:cz.vsb.gis.ruz76.gt.Examples.java
public int postGIS_example2(String pointString, double distance) { //http://postgis.net/docs/manual-1.4/ch05.html Connection conn;//from ww w . java 2 s . c o m String xy[] = pointString.split(" "); int count = 0; try { Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://158.196.143.25:5432/test"; conn = DriverManager.getConnection(url, "test", "test"); Statement s = conn.createStatement(); s.execute("DROP VIEW IF EXISTS ruzicka_archsites_10000"); s.execute( "CREATE VIEW ruzicka_archsites_10000 AS SELECT ST_AsText(geom) as geom, gid FROM sf.archsites WHERE ST_DWITHIN(geom, ST_MakePoint(" + xy[0] + ", " + xy[1] + "), " + distance + ")"); s.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } Map params = new HashMap(); params.put("dbtype", "postgis"); //must be postgis //the name or ip address of the machine running PostGIS params.put("host", "158.196.143.25"); //the port that PostGIS is running on (generally 5432) params.put("port", new Integer(5432)); //the name of the database to connect to. params.put("database", "test"); params.put("user", "test"); //the user to connect with params.put("passwd", "test"); //the password of the user. FeatureSource fs = null; DataStore pgDatastore; try { pgDatastore = DataStoreFinder.getDataStore(params); fs = pgDatastore.getFeatureSource("ruzicka_archsites_10000"); //System.out.println("Count: " + fs.getCount(Query.ALL)); count = fs.getCount(Query.ALL); } catch (IOException e) { e.printStackTrace(); } return count; }
From source file:kr.co.bitnine.octopus.frame.SessionServerTest.java
@Test public void testRole() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("CREATE ROLE rnd"); stmt.execute("DROP ROLE rnd"); stmt.close();/*w w w.j a va 2 s . c o m*/ conn.close(); }
From source file:kr.co.bitnine.octopus.frame.SessionServerTest.java
@Test public void testUser() throws Exception { Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("CREATE USER \"jsyang\" IDENTIFIED BY '0009'"); stmt.close();/*w w w . j a v a 2s . c o m*/ conn.close(); conn = getConnection("jsyang", "0009"); assertFalse(conn.isClosed()); conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("ALTER USER \"jsyang\" IDENTIFIED BY 'jsyang' REPLACE '0009'"); stmt.close(); conn.close(); conn = getConnection("jsyang", "jsyang"); assertFalse(conn.isClosed()); conn.close(); conn = getConnection("octopus", "bitnine"); stmt = conn.createStatement(); stmt.execute("DROP USER \"jsyang\""); stmt.close(); conn.close(); }
From source file:kr.co.bitnine.octopus.frame.SessionServerTest.java
@Test public void testDropDataSource1() throws Exception { /* add a new dataSource and populate some data */ MemoryDatabase newMemDb = new MemoryDatabase("DATA2"); newMemDb.start();//www . ja v a 2 s . c o m final String tblName = "TMP"; newMemDb.runExecuteUpdate("CREATE TABLE \"" + tblName + "\" (ID INTEGER, NAME STRING)"); Connection conn = getConnection("octopus", "bitnine"); Statement stmt = conn.createStatement(); stmt.execute("ALTER SYSTEM ADD DATASOURCE \"" + newMemDb.name + "\" CONNECT TO '" + newMemDb.connectionString + "' USING '" + MemoryDatabase.DRIVER_NAME + "'"); DatabaseMetaData metaData = conn.getMetaData(); assertTrue(existDataSource(metaData, newMemDb.name)); assertTrue(existTable(metaData, newMemDb.name, tblName)); stmt.execute("ALTER SYSTEM DROP DATASOURCE \"" + newMemDb.name + '"'); assertFalse(existDataSource(metaData, newMemDb.name)); assertFalse(existTable(metaData, newMemDb.name, tblName)); /* cleanup */ stmt.close(); conn.close(); newMemDb.stop(); }
From source file:kr.co.bitnine.octopus.frame.SessionServerTest.java
@Test public void testShowComments() throws Exception { Connection conn = getConnection("octopus", "bitnine"); System.out.println("* Comments"); Statement stmt = conn.createStatement(); stmt.execute("COMMENT ON DATASOURCE \"" + dataMemDb.name + "\" IS 'DS_COMMENT'"); stmt.execute("COMMENT ON SCHEMA \"" + dataMemDb.name + "\".\"__DEFAULT\" IS 'SCHEMA_COMMENT'"); stmt.execute("COMMENT ON TABLE \"" + dataMemDb.name + "\".\"__DEFAULT\".\"employee\" IS 'TABLE_COMMENT'"); stmt.execute("COMMENT ON COLUMN \"" + dataMemDb.name + "\".\"__DEFAULT\".\"employee\".\"name\" IS 'COLUMN_COMMENT_EXTRA'"); ResultSet rs = stmt.executeQuery("SHOW COMMENTS '%COMMENT' TABLE 'emp%' "); int rowCnt = 0; while (rs.next()) { ++rowCnt;/*from w w w . j ava2 s .c o m*/ System.out.println(" " + rs.getString("OBJECT_TYPE") + ", " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("TABLE_NAME") + ", " + rs.getString("COLUMN_NAME") + ", " + rs.getString("TABLE_CAT_REMARKS") + ", " + rs.getString("TABLE_SCHEM_REMARKS") + ", " + rs.getString("TABLE_NAME_REMARKS") + ", " + rs.getString("COLUMN_NAME_REMARKS")); } rs.close(); assertEquals(rowCnt, 3); stmt.close(); conn.close(); }