在jdbc中获取数据库的定义,例如:数据库、表、列的定义信息。就用到元数据。
在jdbc中可以使用: 数据库元数据、参数元数据、结果集元数据
(元数据定义相关api, ..MetaData)
public class App {
@Test
public void testDB() throws Exception {
Connection conn = JdbcUtil.getConnection();
DatabaseMetaData metaData = conn.getMetaData();
System.out.println(metaData.getUserName());
System.out.println(metaData.getURL());
System.out.println(metaData.getDatabaseProductName());
}
@Test
public void testParams() throws Exception {
Connection conn = JdbcUtil.getConnection();
String sql = "select * from dept where deptid=? and deptName=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
ParameterMetaData p_metaDate = pstmt.getParameterMetaData();
int count = p_metaDate.getParameterCount();
System.out.println(count);
}
@Test
public void testRs() throws Exception {
String sql = "select * from dept ";
Connection conn = JdbcUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData rs_metaData = rs.getMetaData();
while (rs.next()) {
int count = rs_metaData.getColumnCount();
for (int i=0; i<count; i++) {
String columnName = rs_metaData.getColumnName(i + 1);
Object columnValue = rs.getObject(columnName);
System.out.print(columnName + "=" + columnValue + ",");
}
System.out.println();
}
}
}