Returns a PreparedStatementCreator that returns a count of the rows that
this creator would return.

@param dialect
Database dialect.
492304
public PreparedStatementCreator count(final Dialect dialect) {
        return new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con)
            throws SQLException {
                return getPreparedStatementCreator()
                .setSql(dialect.createCountSelect(builder.toString()))
                .createPreparedStatement(con);
            }
        };
    }
1286643
private int getTotalCount(String sql, Connection conn, MappedStatement ms, BoundSql boundSql) throws SQLException {
    int start = sql.indexOf("from");
    if (start == -1) {
      throw new RuntimeException("statement has no 'from' keyword");
    }
    int stop = sql.indexOf("order by");
    if (stop == -1) {
      stop = sql.length();
    }

    String countSql = "select count(0) " + sql.substring(start, stop);
    BoundSql countBoundSql = new BoundSql(ms.getConfiguration(), countSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
    ParameterHandler parameterHandler = new DefaultParameterHandler(ms, boundSql.getParameterObject(), countBoundSql);
    PreparedStatement stmt = null;
    ResultSet rs = null;
    int count = 0;
    try {
      stmt = conn.prepareStatement(countSql);
      // 通过parameterHandler给PreparedStatement对象设置参数
      parameterHandler.setParameters(stmt);
      rs = stmt.executeQuery();
      if (rs.next()) {
        count = rs.getInt(1);
      }
    } finally {
      CloseableUtil.closeQuietly(rs);
      CloseableUtil.closeQuietly(stmt);
    }
    return count;
  }
569093
public int queryObjCountByCondition(String tableName, String condition){
		/*		JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
		.getDbSource(dbName);*/
		//String tableName=changeTableNameCase(otableName);
		JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
		String sql="";
		sql="select count(1) from " + tableName + " where "+condition;
		logger.debug(sql);
		Integer total=jdbcTemplate.queryForObject(sql,Integer.class);
		return total;
	}
284288
public PreparedStatement prepareStatement(final String sql, 
                                              final int autoGeneratedKeys) 
        throws SQLException {

        checkClosed();

        return new acolyte.jdbc.
            PreparedStatement(this, sql, autoGeneratedKeys, null, null,
                              this.handler.getStatementHandler());

    }
162023
private PreparedStatement prepareBatchStatement(String sql)
    {
        String sqlCmd = sql.substring(0, 7);

        if (sqlCmd.equals("UPDATE ") || sqlCmd.equals("DELETE ") || (_useBatchInserts && sqlCmd.equals("INSERT ")))
        {
            PreparedStatement stmt = (PreparedStatement) _statements.get(sql);
            if (stmt == null)
            {
                // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement
                // interfaces, otherwise proxy.jar works incorrectly
                stmt = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{
                        PreparedStatement.class, Statement.class, BatchPreparedStatement.class},
                        new PreparedStatementInvocationHandler(this, sql, m_jcd));
                _statements.put(sql, stmt);
            }
            return stmt;
        }
        else
        {
            return null;
        }
    }
1149415
private String createCountSql(String sql) {
        StringBuilder sb = new StringBuilder("select count(0) from ( ");
        sb.append(sql).append(" ) as t");
        return sb.toString();
    }
926700
public String buildPreparedStatementName() {
		if (!StringUtils.hasText(preparedStatementName)) {
			preparedStatementName = getParent().buildPreparedStatementName(getName());
		}
		return preparedStatementName;
	}
954122
protected static String initializePaginSQLTemplate(Dialect d) {
		switch (d) {
		case Cache71Dialect:
		case DB2390Dialect:
		case DB2390V8Dialect:
		case FrontBaseDialect:
		case InformixDialect:
		case IngresDialect:
		case JDataStoreDialect:
		case MckoiDialect:
		case MimerSQLDialect:
		case PointbaseDialect:
		case ProgressDialect:
		case RDMSOS2200Dialect:
		case SAPDBDialect:
		case SQLServerDialect:
		case Sybase11Dialect:
		case SybaseASE15Dialect:
		case SybaseAnywhereDialect:
		case SybaseDialect:
		case Teradata14Dialect:
		case TeradataDialect:
		case TimesTenDialect:
			return Dialect.NOT_SUPPORT;
		case SQLServer2005Dialect:
		case SQLServer2008Dialect:
			return "WITH query AS (SELECT TMP_.*, ROW_NUMBER() OVER (ORDER BY CURRENT_TIMESTAMP) as ROW_NUM_ FROM ( select ($DISTINCT) TOP($TOTAL_ROWS) $BODY ) TMP_ ) SELECT * FROM query WHERE ROW_NUM_ >$SKIP_ROWS AND ROW_NUM_ <= $TOTAL_ROWS";
		case H2Dialect:
		case HANAColumnStoreDialect:
		case HANARowStoreDialect:
		case PostgreSQL81Dialect:
		case PostgreSQL82Dialect:
		case PostgreSQL91Dialect:
		case PostgreSQL92Dialect:
		case PostgreSQL93Dialect:
		case PostgreSQL94Dialect:
		case PostgreSQL95Dialect:
		case PostgreSQL9Dialect:
		case PostgreSQLDialect:
		case PostgresPlusDialect:
		case SQLiteDialect:
			return "select $BODY limit $PAGESIZE offset $SKIP_ROWS";
		case AccessDialect:
		case CUBRIDDialect:
		case CobolDialect:
		case DbfDialect:
		case ExcelDialect:
		case MariaDB102Dialect:
		case MariaDB103Dialect:
		case MariaDB10Dialect:
		case MariaDB53Dialect:
		case MariaDBDialect:
		case MySQL55Dialect:
		case MySQL57Dialect:
		case MySQL57InnoDBDialect:
		case MySQL5Dialect:
		case MySQL5InnoDBDialect:
		case MySQL8Dialect:
		case MySQLDialect:
		case MySQLInnoDBDialect:
		case MySQLMyISAMDialect:
		case ParadoxDialect:
		case TextDialect:
		case XMLDialect:
			return "select $BODY limit $SKIP_ROWS, $PAGESIZE";
		case SQLServer2012Dialect:
			return "select $BODY offset $SKIP_ROWS rows fetch next $PAGESIZE rows only";
		case Ingres10Dialect:
		case Ingres9Dialect:
			return "select $BODY offset $skip_rows fetch first $pagesize rows only";
		case DerbyDialect:
		case DerbyTenFiveDialect:
		case DerbyTenSevenDialect:
		case DerbyTenSixDialect:
			return "select $BODY offset $skip_rows rows fetch next $pagesize rows only";
		case InterbaseDialect:
			return "select $BODY rows $SKIP_ROWS to $PAGESIZE";
		case SybaseASE157Dialect:
			return "select ($DISTINCT) top $total_rows $BODY";
		case DB2400Dialect:
		case DB297Dialect:
		case DB2Dialect:
			return "select * from ( select inner2_.*, rownumber() over(order by order of inner2_) as rownumber_ from ( select $BODY fetch first $total_rows rows only ) as inner2_ ) as inner1_ where rownumber_ > $skip_rows order by rownumber_";
		case Oracle8iDialect:
		case OracleDialect:
			return "select * from ( select row_.*, rownum rownum_ from ( select $BODY ) row_ ) where rownum_ <= $TOTAL_ROWS and rownum_ > $SKIP_ROWS";
		case DataDirectOracle9Dialect:
		case Oracle10gDialect:
		case Oracle12cDialect:
		case Oracle9Dialect:
		case Oracle9iDialect:
			return "select * from ( select row_.*, rownum rownum_ from ( select $BODY ) row_ where rownum <= $TOTAL_ROWS) where rownum_ > $SKIP_ROWS";
		case Informix10Dialect:
			return "select SKIP $skip_rows first $pagesize $BODY";
		case FirebirdDialect:
			return "select first $PAGESIZE skip $SKIP_ROWS $BODY";
		case HSQLDialect:
			return "select limit $SKIP_ROWS $PAGESIZE $BODY";
		default:
			return Dialect.NOT_SUPPORT;
		}
	}
494027
@Override
    public Statement createStatement() throws SQLException
    {
        checkClosed();
        try
        {
            return new JDBC4Statement(this);
        }
        catch(Exception x)
        {
            throw SQLError.get(x);
        }
    }
524241
public static PreparedStatement newInstance(PreparedStatement stmt, Log statementLog, int queryStack) {
    InvocationHandler handler = new PreparedStatementLogger(stmt, statementLog, queryStack);
    ClassLoader cl = PreparedStatement.class.getClassLoader();
    return (PreparedStatement) Proxy.newProxyInstance(cl, new Class[]{PreparedStatement.class, CallableStatement.class}, handler);
  }
475384
@Override
	public long count(final String col) {
		final String expr = col != null
				? tableMetadata.getColumn(CaseFormat.CAMEL_CASE.convert(col)).getColumnIdentifier()
				: "*";
		StringBuilder sql = new StringBuilder("select count(").append(expr).append(") from (")
				.append(System.lineSeparator())
				.append(aggregationSourceSql())
				.append(System.lineSeparator())
				.append(") t_");
		context().setSql(sql.toString());
		try (ResultSet rs = agent().query(context())) {
			rs.next();
			return rs.getLong(1);
		} catch (final SQLException e) {
			throw new EntitySqlRuntimeException(SqlKind.SELECT, e);
		}
	}
406037
public synchronized QueryResult execute() throws QueryException, InterruptedException {
		// create query string
		String queryString = createQueryString();

        PreparedStatement countPstmt = null;
        if (computeCount) {
            try {
                // count statement
                String countQueryString = "SELECT COUNT(*) FROM (" + queryString + ") A";
                if (isCsv) {
                	// csv jdbc driver does not support sub-select
                	countQueryString = getCsvCountQuery(queryString);
                }
                countPstmt = createStatement(countQueryString);
                if (parameterNames.size() != 0) {
                    setParameterValues(countPstmt);
                }
            } catch (QueryException ex) {
                LOG.info("Cannot create count statement : " + ex.getMessage() + " .Will use rs.last()");
                countPstmt = null;
            }
        }

        // create statement
		PreparedStatement pstmt = createStatement(queryString);

        // set parameter values
		if (parameterNames.size() != 0) {
			setParameterValues(pstmt);
		}
        
        try {
            setOutParametersValues(pstmt);
        } catch (SQLException e) {
            throw new QueryException(e);
        } catch (DialectException e) {
            throw new QueryException("Error set out parameter values for executing query : could not get dialect", e);
        }

        // set query's input wrapper
		synchronized (inputWrapper) {
			inputWrapper.statement = pstmt;
            inputWrapper.countStatement = countPstmt;
            inputWrapper.query = queryString;
			inputWrapper.pending = true;
			inputWrapper.notify();
		}

		synchronized (resultWrapper) {
			try {
				// wait for the query to complete
				while (!resultWrapper.serviced) {
					resultWrapper.wait();
				}
				if (resultWrapper.exception != null) {
					throw resultWrapper.exception;
				}
			} catch (InterruptedException e) {
				cancel();
				throw e;
			} finally {
				resultWrapper.serviced = false;
			}

			if ((maxRows > 0) && (resultWrapper.count > maxRows)) {
				resultWrapper.count = maxRows;
			}

			//must finish run method thread normally
			closeRequest = true;
			synchronized (inputWrapper) {
				inputWrapper.pending = true;
				inputWrapper.notify();
			}

			return new QueryResult(resultWrapper.resultSet, resultWrapper.count, resultWrapper.executeTime);
		}
	}
281832
public static void generateSQL(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		JQLChecker jqlChecker = JQLChecker.getInstance();

		methodBuilder.addCode("\n// generate sql\n");
		String sql = jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {
			@Override
			public String onColumnNameToUpdate(String columnName) {
				// only entity's columns
				return currentEntity.findPropertyByName(columnName).columnName;
			}

			@Override
			public String onColumnName(String columnName) {
				return currentSchema.findColumnNameByPropertyName(method, columnName);
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				return "?";
			}

		});

		if (method.jql.dynamicReplace.containsKey(JQLDynamicStatementType.DYNAMIC_WHERE)) {
			methodBuilder.addStatement("String _sql=String.format($S, $L)",
					sql.replace(method.jql.dynamicReplace.get(JQLDynamicStatementType.DYNAMIC_WHERE), "%s"),
					"StringUtils.ifNotEmptyAppend(_sqlDynamicWhere,\" AND \")");
		} else {
			methodBuilder.addStatement("String _sql=$S", sql);
		}
	}
1332577
def sql(self, dialect=None, inserts=False, creates=True,
            drops=True, metadata_source=None):
        
        result = [self.ddl(dialect, creates=creates, drops=drops)]
        if inserts:
            for row in self.inserts(dialect):
                result.append(row)
        return '\n'.join(result)
284478
private void setPageTotalCount(Connection connection, MappedStatement mappedStatement, BoundSql boundSql) {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(createCountSql(boundSql.getSql()));
            ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, boundSql.getParameterObject(), boundSql);
            parameterHandler.setParameters(preparedStatement);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                ((PageEntity) boundSql.getParameterObject()).setTotalCount(resultSet.getLong(1));
            }
            if (resultSet != null) resultSet.close();
            if (preparedStatement != null) preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
1280307
public static TableModel[] db2Models(Connection con, Dialect dialect) {// NOSONAR
		List<TableModel> tableModels = new ArrayList<TableModel>();
		SQLException sqlException = null;
		ResultSet rs = null;
		PreparedStatement pst = null;

		try {
			DatabaseMetaData meta = con.getMetaData();
			String catalog = con.getCatalog();
			// get Tables
			rs = meta.getTables(catalog, dialect.isOracleFamily() ? meta.getUserName() : null, null,
					new String[] { "TABLE" });
			while (rs.next()) {
				String tableName = rs.getString(TABLE_NAME);
				if (!StrUtils.isEmpty(tableName)) {
					TableModel model = new TableModel(tableName);
					tableModels.add(model);
					String comment = rs.getString("REMARKS");
					if (!StrUtils.isEmpty(comment))
						model.setComment(comment);
				}
			}
			rs.close();

			// Build Columns
			for (TableModel model : tableModels) {
				String tableName = model.getTableName();
				rs = meta.getColumns(null, null, tableName, null);
				while (rs.next()) {// NOSONAR
					String colName = rs.getString("COLUMN_NAME");
					ColumnModel col = new ColumnModel(colName);
					model.addColumn(col);

					int javaSqlType = rs.getInt("DATA_TYPE");
					try {
						col.setColumnType(TypeUtils.javaSqlTypeToDialectType(javaSqlType));
					} catch (Exception e1) {
						throw new DialectException("jDialect does not supported java.sql.types value " + javaSqlType,
								e1);
					}
					col.setLength(rs.getInt("COLUMN_SIZE"));
					col.setNullable(rs.getInt("NULLABLE") > 0);
					col.setPrecision(rs.getInt("DECIMAL_DIGITS"));
					col.setLengths(new Integer[] { col.getLength(), col.getPrecision(), col.getPrecision() });

					try {
						if (((Boolean) (true)).equals(rs.getBoolean("IS_AUTOINCREMENT")))
							col.identityId();
					} catch (Exception e) {
					}

					try {
						if ("YES".equalsIgnoreCase(rs.getString("IS_AUTOINCREMENT")))
							col.identityId();
					} catch (Exception e) {
					}
				}
				rs.close();
			}

			// Get Primary Keys for each model
			for (TableModel model : tableModels) {
				rs = meta.getPrimaryKeys(catalog, null, model.getTableName());
				while (rs.next())
					model.getColumnByColName(rs.getString("COLUMN_NAME")).setPkey(true);
				rs.close();
			}

			// Get Foreign Keys for each model
			for (TableModel model : tableModels) {
				ResultSet foreignKeyResultSet = meta.getImportedKeys(catalog, null, model.getTableName());
				while (foreignKeyResultSet.next()) {
					String fkname = foreignKeyResultSet.getString("FK_NAME");
					int keyseq = foreignKeyResultSet.getInt("KEY_SEQ");
					String fkColumnName = foreignKeyResultSet.getString("FKCOLUMN_NAME");
					String pkTablenName = foreignKeyResultSet.getString("PKTABLE_NAME");
					String pkColumnName = foreignKeyResultSet.getString("PKCOLUMN_NAME");
					FKeyModel fkeyModel = model.getFkey(fkname);

					if (keyseq == 1) {
						model.fkey(fkname).columns(fkColumnName).refs(pkTablenName, pkColumnName);
					} else {
						fkeyModel.getColumnNames().add(fkColumnName);
						String[] newRefs = ArrayUtils.appendStrArray(fkeyModel.getRefTableAndColumns(), pkColumnName);
						fkeyModel.setRefTableAndColumns(newRefs);
					}
				}
			}

		} catch (SQLException e) {
			e.printStackTrace();
			sqlException = e;
		} finally {
			if (pst != null)
				try {
					pst.close();
				} catch (SQLException e1) {
					if (sqlException != null)
						sqlException.setNextException(e1);
					else
						sqlException = e1;
				}
			try {
				if (rs != null)
					rs.close();
			} catch (SQLException e2) {
				if (sqlException != null)
					sqlException.setNextException(e2);
				else
					sqlException = e2;
			}
		}
		if (sqlException != null)
			throw new DialectException(sqlException);
		return tableModels.toArray(new TableModel[tableModels.size()]);
	}
1307378
public SelectRootClauseBuilder<? extends QueryForNumber> count() {
		//TODO its hard to know whether or not to innerjoin to get an accurate count here.
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT count(*)");
		sb.append(" FROM ").append(definition.getSqlName());
		//definition.innerJoin(sb);
		SelectRootClauseBuilder<? extends QueryForNumber> r = SelectRootClauseBuilder.newInstance(new RootClauseHandoff<CountBuilder<T>>(sb.toString()) {
			@Override
			protected CountBuilder<T> createBuilder(String sql) {
				return new CountBuilder<T>(SelectBuilderFactory.this, sql);
			}
			
			@Override
			public CountBuilder<T> transform(SelectRootClauseBuilder<CountBuilder<T>> clause) {
				clause.where().limit(1);
				return super.transform(clause);
			}
			
		});
		return r;
	}