元数据(MetaData)
1. 在jdbc中获取数据库的定义,例如:数据库、表、列的定义信息。就用到元数据
2. 在jdbc中可以使用: 数据库元数据、参数元数据、结果集元数据
3. 用到的导入方法 java.sql.Connection;
ps:1.楼主主要 用于得到数据库列表的名称,根据名称去获得每一列的值。
2.用到元数据(MetaData)的方法有: MetaData.getColumnCount() //得到列的数量 3个
MetaData.getColumnName(int i) //得到第i列的名字
接下来将引用自己写的例子:
数据库的表格
name | id | phone |
张三 | 1 | 123456 |
李四 | 2 | 123456 |
老五 | 3 | 123456 |
调用数据库代码如下
public void test1() throws SQLException {
/**
* 连接数据库
*/
Connection con = null;
// 已经封装了在Utils包里的连接数据库的类
con = JdbcUtils.getConnection();
// sql 语句
String sql = "select * from test";
PreparedStatement pst = con.prepareStatement(sql);
ResultSet re = pst.executeQuery();
// 得到结果集 元数据 (目标:通过结果集元素数据,得到列的名称)
ResultSetMetaData re_MetaData = re.getMetaData();
/**
* name id phone 张三 *** *** ** ** ***
*/
// 迭代每一行结果
while (re.next()) {
// 1获取列的个数
int sum = re_MetaData.getColumnCount();
// 遍历每列的数
for (int i = 0; i < sum; i++) {
//得到第i+1列的名称 name
String columnName=re_MetaData.getColumnName(i+1);
//2得到该列的值 张三
Object columnValue =re.getString(columnName);
System.out.print(columnName+"="+columnValue+" ");
}
System.out.println();
}
}
效果图
NAME=张三 id=1 phone=123456
NAME=李四 id=2 phone=123456
NAME=老五 id=3 phone=123456