本文整理汇总了Java中java.sql.ResultSetMetaData.getColumnCount方法的典型用法代码示例。如果您正苦于以下问题:Java ResultSetMetaData.getColumnCount方法的具体用法?Java ResultSetMetaData.getColumnCount怎么用?Java ResultSetMetaData.getColumnCount使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.sql.ResultSetMetaData
的用法示例。
在下文中一共展示了ResultSetMetaData.getColumnCount方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: printTable
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
private void printTable(String table, String cols, int expected) throws SQLException {
int rows = 0;
ResultSet rs = stmnt.executeQuery("SELECT " + cols + " FROM " + table);
ResultSetMetaData rsmd = rs.getMetaData();
String result = "Table " + table + ", expecting "
+ expected + " rows total:\n";
while (rs.next()) {
for (int i = 0; i < rsmd.getColumnCount(); i++) {
result += rsmd.getColumnLabel(i + 1) + ":"
+ rs.getString(i + 1) + ":";
}
result += "\n";
rows++;
}
rs.close();
System.out.println(result);
assertEquals(expected, rows);
}
示例2: dump
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
public static void dump(ResultSet rs) throws SQLException {
// the order of the rows in a cursor
// are implementation dependent unless you use the SQL ORDER statement
ResultSetMetaData meta = rs.getMetaData();
int colmax = meta.getColumnCount();
int i;
Object o = null;
// the result set is a cursor into the data. You can only
// point to one row at a time
// assume we are pointing to BEFORE the first row
// rs.next() points to next row and returns true
// or false if there is no next row, which breaks the loop
for (; rs.next(); ) {
for (i = 0; i < colmax; ++i) {
o = rs.getObject(i + 1); // Is SQL the first column is indexed
// with 1 not 0
System.out.print(o.toString() + " ");
}
System.out.println(" ");
}
}
示例3: getColumnNameToIndexMap
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
public static Map<String, Integer> getColumnNameToIndexMap(final String queryString, final EntityManager em) throws SQLException {
final Session session = em.unwrap(Session.class); // ATTENTION! This is Hibernate-specific!
final AtomicReference<ResultSetMetaData> msRef = new AtomicReference<>();
session.doWork((c) -> {
try (final PreparedStatement statement = create(c, queryString)) {
// I'm not setting parameters here, because I just want to find out about the return values' column names
msRef.set(statement.getMetaData());
}
});
final ResultSetMetaData metaData = msRef.get();
// LinkedHashmap preserves order of insertion:
final Map<String, Integer> columnNameToColumnIndex = new LinkedHashMap<>();
for (int t = 0; t < metaData.getColumnCount(); ++t) {
// important, first index in the metadata is "1", the first index for the result array must be "0"
columnNameToColumnIndex.put(metaData.getColumnName(t + 1), t);
}
return columnNameToColumnIndex;
}
示例4: executeQuery
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
private List<Map<String, Object>> executeQuery(String sql, Object... params) {
List<Map<String, Object>> list = null;
try {
try(Connection connection = dataSource.getConnection();
PreparedStatement ps= connection.prepareStatement(sql)){
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject((i + 1), params[i]);
}
}
ResultSet rs = ps.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
list = new ArrayList<>();
while (rs.next()) {
Map<String, Object> rowData = Maps.newHashMap();
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
}
} catch (SQLException e) {
e.printStackTrace();
LOGGER.error("executeQuery->" + e.getMessage());
}
return list;
}
示例5: getInsert
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
/** returns the SQL command to insert l into the DB */
protected String getInsert(Literal l) throws Exception {
StringBuilder q = new StringBuilder("insert into ");
ResultSetMetaData meta = belsDB.get(l.getPredicateIndicator());
q.append(meta.getTableName(1));
q.append(" values(");
// values
for (int i = 0; i < l.getArity(); i++) {
Term t = l.getTerm(i);
if (t.isString()) {
q.append("'" + ((StringTerm) t).getString() + "'");
} else {
Timestamp timestamp = structure2timestamp(t);
if (timestamp != null) {
q.append("TIMESTAMP '" + structure2timestamp(t) + "'");
} else {
q.append("'" + t.toString() + "'");
}
}
if (i < meta.getColumnCount() - 1) {
q.append(",");
}
}
if (isCreatedByJason(l.getPredicateIndicator())) {
q.append(l.negated() + ",");
if (l.hasAnnot()) {
q.append("\'" + l.getAnnots() + "\'");
} else {
q.append("\'[]\'");
}
}
q.append(")");
return q.toString();
}
示例6: testMetaDataIsWritable
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
/**
* Tests a bug where ResultSet.isBefireFirst() would return true when the
* result set was empty (which is incorrect)
*
* @throws Exception
* if an error occurs.
*/
public void testMetaDataIsWritable() throws Exception {
// Query with valid rows
this.rs = this.stmt.executeQuery("SHOW VARIABLES LIKE 'version'");
ResultSetMetaData rsmd = this.rs.getMetaData();
int numColumns = rsmd.getColumnCount();
for (int i = 1; i <= numColumns; i++) {
assertTrue("rsmd.isWritable() should != rsmd.isReadOnly()", rsmd.isWritable(i) != rsmd.isReadOnly(i));
}
}
示例7: toString
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
/**
* Translate ResultSet to String representation
* @param r
*/
private String toString(ResultSet r) {
try {
if (r == null) {
return "No Result";
}
ResultSetMetaData m = r.getMetaData();
int col = m.getColumnCount();
StringBuffer strbuf = new StringBuffer();
for (int i = 1; i <= col; i++) {
strbuf = strbuf.append(m.getColumnLabel(i) + "\t");
}
strbuf = strbuf.append("\n");
while (r.next()) {
for (int i = 1; i <= col; i++) {
strbuf = strbuf.append(r.getString(i) + "\t");
if (r.wasNull()) {
strbuf = strbuf.append("(null)\t");
}
}
strbuf = strbuf.append("\n");
}
return strbuf.toString();
} catch (SQLException e) {
return null;
}
}
示例8: checkExist
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
public boolean checkExist(String table) {
try {
// String sql = "SELECT COUNT(*) AS c FROM sqlite_master WHERE type ='table' AND name ='" + table + "' ";
String sql = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='" + table + "';";
Statement statement = mConnection.createStatement();
ResultSet rs = statement.executeQuery(sql);
int count = 0;
if (rs != null && rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
if (columnCount > 0) {
count = rs.getInt(1);
}
}
statement.close();
rs.close();
return count > 0;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
示例9: testGenerateWhereConditionWidthoutPK2
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
public void testGenerateWhereConditionWidthoutPK2() throws SQLException {
DBMetaDataFactory dbMeta = new DBMetaDataFactory(conn);
Statement s = conn.createStatement();
String sql = "SELECT smallintc, varcharc FROM simpletable";
ResultSet rs = s.executeQuery(sql);
Collection<DBTable> tables = dbMeta.generateDBTables(rs, sql, true);
dbMeta.postprocessTables(tables);
DBTable table = tables.iterator().next();
assertEquals(2, table.getPrimaryKey().getColumnCount());
SQLStatementGenerator ssg = new SQLStatementGenerator();
List<DBColumn> columns = table.getColumnList();
DataViewTableUIModel model = new DataViewTableUIModel(
columns.toArray(new DBColumn[0]));
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
Object[] row = new Object[rsmd.getColumnCount()];
for (int i = 0; i < rsmd.getColumnCount(); i++) {
row[i] = DBReadWriteHelper.readResultSet(rs, columns.get(i), i + 1);
}
model.addRow(row);
}
StringBuilder resultSQL = new StringBuilder();
List<Integer> resultTypes = new ArrayList<Integer>();
List<Object> resultObject = new ArrayList<Object>();
ssg.generateWhereCondition(table, resultSQL, resultTypes, resultObject, 0, model);
assertEquals("\"SMALLINTC\" = ? AND \"VARCHARC\" = ? ", resultSQL.toString());
assertEquals(Arrays.asList(new Integer[]{Types.INTEGER, Types.VARCHAR}), resultTypes);
assertEquals(Arrays.asList(new Object[]{-32766, "ala"}), resultObject);
}
示例10: dumpTable
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
private static void dumpTable(String tn) throws SQLException {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from " + tn);
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
out.println();
out.println("****************************************");
out.println("DUMP FOR TABLE: " + tn);
out.println("****************************************");
out.flush();
while (rs.next()) {
out.print("[");
for (int i = 1; i <= count; i++) {
out.print(rs.getString(i));
if (i < count) {
out.print(" : ");
}
}
out.println("]");
}
out.println();
out.flush();
rs.close();
stmt.close();
conn.close();
}
示例11: executeQuery
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
private List<Map<String, Object>> executeQuery(String sql, Object... params) {
List<Map<String, Object>> list = null;
try (Connection connection = dataSource.getConnection();
PreparedStatement ps = connection.prepareStatement(sql)) {
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject((i + 1), params[i]);
}
}
try (ResultSet rs = ps.executeQuery()) {
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
list = new ArrayList<>();
while (rs.next()) {
Map<String, Object> rowData = new HashMap<>(16);
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
}
} catch (SQLException e) {
logger.error("executeQuery-> " + e.getMessage());
}
return list;
}
示例12: getAllUsernames
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
/**Returns a list of all usernames in the database
* @throws SQLException */
public static String[] getAllUsernames() throws SQLException
{
//Create query to fetch all users
DatabaseConnection connection = new DatabaseConnection();
String query = "SELECT * FROM USERS";
//Create list to store usernames
ArrayList<String> list = new ArrayList<String>();
try
{
//Execute our query
ResultSet rs = connection.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
//Display all results from our query
while (rs.next())
{
for(int i = 1; i <= metaData.getColumnCount(); i++)
{
if (metaData.getColumnName(i).equals("USERNAME"))
{
list.add(rs.getString(i));
}
}
}
}
catch (SQLException e)
{
//Throw a SQL exception if we run into one
throw e;
}
finally
{
//Close the connection regardless of whether we encountered an exception
connection.close();
}
return (String[])list.toArray(new String[0]);
}
示例13: printResults
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
protected final int printResults(ResultSet rs, String queryName)
throws Exception {
ResultSetMetaData rsmd = rs.getMetaData();
int numcols = rsmd.getColumnCount();
int numrows = 0;
LOGGER.log(DEBUGLEVEL, "RESULTS FROM " + queryName);
assert(rs != null);
StringBuffer buf = new StringBuffer();
buf.append("|");
for ( int i = 1 ; i <= numcols ; i++ ) {
buf.append(rsmd.getColumnName(i) + "|");
}
LOGGER.log(DEBUGLEVEL, buf.toString());
while ( rs.next() ) {
numrows++;
buf = new StringBuffer();
buf.append("|");
for ( int i = 1 ; i <= numcols ; i++ ) {
buf.append(rs.getString(i) + "|");
}
LOGGER.log(DEBUGLEVEL, buf.toString());
}
return numrows;
}
示例14: getAttributes
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
public static List<Attribute> getAttributes(ResultSetMetaData metaData) throws SQLException {
LinkedList result = new LinkedList();
if(metaData != null) {
HashMap duplicateNameMap = new HashMap();
for(int columnIndex = 1; columnIndex <= metaData.getColumnCount(); ++columnIndex) {
String dbColumnName = metaData.getColumnLabel(columnIndex);
String columnName = dbColumnName;
Integer duplicateCount = (Integer)duplicateNameMap.get(dbColumnName);
boolean isUnique = duplicateCount == null;
if(isUnique) {
duplicateNameMap.put(dbColumnName, new Integer(1));
} else {
while(!isUnique) {
duplicateCount = new Integer(duplicateCount.intValue() + 1);
columnName = dbColumnName + "_" + (duplicateCount.intValue() - 1);
isUnique = duplicateNameMap.get(columnName) == null;
}
duplicateNameMap.put(dbColumnName, duplicateCount);
}
int attributeType = DatabaseHandler.getRapidMinerTypeIndex(metaData.getColumnType(columnIndex));
Attribute attribute = AttributeFactory.createAttribute(columnName, attributeType);
attribute.getAnnotations().setAnnotation("sql_type", metaData.getColumnTypeName(columnIndex));
result.add(attribute);
}
}
return result;
}
示例15: frame
import java.sql.ResultSetMetaData; //导入方法依赖的package包/类
/** Creates a frame containing a given number or unlimited number of rows
* from a result set. */
static Meta.Frame frame(StatementInfo info, ResultSet resultSet, long offset,
int fetchMaxRowCount, Calendar calendar, Optional<Meta.Signature> sig) throws SQLException {
final ResultSetMetaData metaData = resultSet.getMetaData();
final int columnCount = metaData.getColumnCount();
final int[] types = new int[columnCount];
Set<Integer> arrayOffsets = new HashSet<>();
for (int i = 0; i < types.length; i++) {
types[i] = metaData.getColumnType(i + 1);
if (Types.ARRAY == types[i]) {
arrayOffsets.add(i);
}
}
final List<Object> rows = new ArrayList<>();
// Meta prepare/prepareAndExecute 0 return 0 row and done
boolean done = fetchMaxRowCount == 0;
for (int i = 0; fetchMaxRowCount < 0 || i < fetchMaxRowCount; i++) {
final boolean hasRow;
if (null != info) {
hasRow = info.next();
} else {
hasRow = resultSet.next();
}
if (!hasRow) {
done = true;
resultSet.close();
break;
}
Object[] columns = new Object[columnCount];
for (int j = 0; j < columnCount; j++) {
columns[j] = getValue(resultSet, types[j], j, calendar);
if (arrayOffsets.contains(j)) {
// If we have an Array type, our Signature is lacking precision. We can't extract the
// component type of an Array from metadata, we have to update it as we're serializing
// the ResultSet.
final Array array = resultSet.getArray(j + 1);
// Only attempt to determine the component type for the array when non-null
if (null != array && sig.isPresent()) {
ColumnMetaData columnMetaData = sig.get().columns.get(j);
ArrayType arrayType = (ArrayType) columnMetaData.type;
SqlType componentSqlType = SqlType.valueOf(array.getBaseType());
// Avatica Server will always return non-primitives to ensure nullable is guaranteed.
ColumnMetaData.Rep rep = ColumnMetaData.Rep.serialRepOf(componentSqlType);
AvaticaType componentType = ColumnMetaData.scalar(array.getBaseType(),
array.getBaseTypeName(), rep);
// Update the ArrayType from the Signature
arrayType.updateComponentType(componentType);
// We only need to update the array's type once.
arrayOffsets.remove(j);
}
}
}
rows.add(columns);
}
return new Meta.Frame(offset, done, rows);
}