元数据指的是数据的数据,建议操作时用ojdbc7.jar,其他版本的jar包可能对某些方法不支持!
分为三类:
1.数据库元数据(DataBaseMetaData)
(借助Connection获取元数据)
public static void databaseMetaData() {
try {
Class.forName(DRIVERE);
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
//数据库元信息
DatabaseMetaData dbMetadata = connection.getMetaData() ;
String dbName = dbMetadata.getDatabaseProductName();
System.out.println("数据库名:"+dbName);
String dbVersion = dbMetadata.getDatabaseProductVersion();
System.out.println("数据库版本:"+dbVersion);
String driverName = dbMetadata.getDriverName() ;
System.out.println("驱动名"+driverName);
String url = dbMetadata.getURL();
System.out.println("驱动:"+url);
String userName = dbMetadata.getUserName();
System.out.println("用户名:"+userName);
//先要设置主键 alter table account add constraint ps_id primary key(carid);
//alter table student add constraint pk_id primary key(stuno);
System.out.println("--------------------------------");
ResultSet rs = dbMetadata.getPrimaryKeys(null,"SCOTT","STUDENT");
while (rs.next()){
System.out.println("123");
Object tableName = rs.getObject(3);//表名
Object columnName = rs.getObject(4);//列名称
Object pkName = rs.getObject(6);//主键的约束名称
System.out.println(tableName+"========="+columnName+"========"+pkName);
}
}catch (Exception e){
e.printStackTrace();
}
}
结果:
2.参数元数据(ParameterMetaData)
(借助PreparedStatement)
public static void parameterMetaData(){
try{
Class.forName(DRIVERE);
Connection connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql = "select *from student where stuno = ? and stuname = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
//通过pstmt获取参数元数据
ParameterMetaData metaData = pstmt.getParameterMetaData();
int count = metaData.getParameterCount();
System.out.println("参数个数:"+count);
for(int i=1;i<=count;i++){
String typeName = metaData.getParameterTypeName(i);
System.out.println(typeName);//////jdbc7
}
}catch (Exception e){
e.printStackTrace();
}
}
结果:
3.结果集元数据(ResultSetMetaData)
(借助ResultSet)
public static void resultSetMetaData(){
try{
Class.forName(DRIVERE);
Connection connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
PreparedStatement pstmt = connection.prepareStatement("select *from student");
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int count = metaData.getColumnCount();//返回列数
System.out.println("列数为:"+count);
System.out.println("---------------------------");
for(int i=1;i<=count;i++){
String columnName = metaData.getColumnName(i);
String columnTypeName = metaData.getColumnTypeName(i);
System.out.println(columnName+"\t"+columnTypeName);
}
System.out.println("------------------------");
while(rs.next()){
for(int i=1;i<=count;i++){
System.out.print(rs.getObject(i)+" ");
}
System.out.println();
}
}catch (Exception e){
e.printStackTrace();
}
}
结果: