如何从 JDBC ResultSet 获取列数?

我使用 CsvJdbc(它是用于 csv 文件的 JDBC 驱动程序)来访问 csv 文件。我不知道 csv 文件包含多少列。我怎样才能得到列的数目?有没有什么 JDBC 函数可以做到这一点?我在 java.sql 中找不到这方面的任何方法。结果集。

为了访问该文件,我使用了类似于 CsvJdbc 网站上的 例子的代码。

135710 次浏览

You can get columns number from ResultSetMetaData:

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();


int columnsNumber = rsmd.getColumnCount();
PreparedStatement ps=con.prepareStatement("select * from stud");


ResultSet rs=ps.executeQuery();


ResultSetMetaData rsmd=rs.getMetaData();


System.out.println("columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));

Number of a columns in the result set you can get with code (as DB is used PostgreSQL):

//load the driver for PostgreSQL
Class.forName("org.postgresql.Driver");


String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","mydbuser");
props.setProperty("password","mydbpass");
Connection conn = DriverManager.getConnection(url, props);


//create statement
Statement stat = conn.createStatement();


//obtain a result set
ResultSet rs = stat.executeQuery("SELECT c1, c2, c3, c4, c5 FROM MY_TABLE");


//from result set give metadata
ResultSetMetaData rsmd = rs.getMetaData();


//columns count from metadata object
int numOfCols = rsmd.getColumnCount();

But you can get more meta-informations about columns:

for(int i = 1; i <= numOfCols; i++)
{
System.out.println(rsmd.getColumnName(i));
}

And at least but not least, you can get some info not just about table but about DB too, how to do it you can find here and here.

After establising the connection and executing the query try this:

 ResultSet resultSet;
int columnCount = resultSet.getMetaData().getColumnCount();
System.out.println("column count : "+columnCount);

This will print the data in columns and comes to new line once last column is reached.

ResultSetMetaData resultSetMetaData = res.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
for(int i =1; i<=columnCount; i++){
if(!(i==columnCount)){


System.out.print(res.getString(i)+"\t");
}
else{
System.out.println(res.getString(i));
}


}