要獲得結果集中的列名,您需要使用getMetaData()方法。getMetadata()的原型如下 ?
ResultSetMetaData getMetaData throws SQLException;
登錄后復制
Create a MySQL table with 5 column names. The query to create a table is as follows −
mysql> create table javagetallcolumnnames -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(20), -> Age int, -> Salary float, -> Address varchar(100), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.34 sec)
登錄后復制
以下是獲取ResultSet中列名的Java代碼。代碼如下 −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.ResultSetMetaData;
public class GetAllColumnNames {
public static void main(String[] args) {
String JdbcURL="jdbc:mysql://localhost:3306/test?useSSL=false";
String Username="root";
String password="123456";
Connection con=null;
Statement stmt=null;
ResultSet rs;
try {
con = DriverManager.getConnection(JdbcURL, Username, password);
stmt=con.createStatement();
rs = stmt.executeQuery("SELECT *FROM javagetallcolumnnames");
ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
int counter = md.getColumnCount();
String colName[] = new String[counter];
System.out.println("The column names are as follows:");
for (int loop = 1; loop <= counter; loop++) {
colName[loop-1] = md.getColumnLabel(loop);
System.out.println(colName[loop-1]);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
登錄后復制
Here is the snapshot of the code −
The following is the output −
The column names are as follows: Id Name Age Salary Address
登錄后復制
這是示例輸出的快照 ?
以上就是如何使用 MySQL 在 Java 中獲取 ResultSet 上的列名稱?的詳細內容,更多請關注www.92cms.cn其它相關文章!






