(1)DatabaseMetaData:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package
javase.jdbc;
import
java.sql.Connection;
import
java.sql.DatabaseMetaData;
import
java.sql.ResultSet;
import
java.sql.SQLException;
public
class
DatabaseMetaDataDemo {
public
static
void
main(String[] args) {
Connection connection = JDBCConnection.getConnection();
try
{
DatabaseMetaData dMetaData = connection.getMetaData();
// 实例化元数据
System.out.println(
"数据库名:"
+ dMetaData.getDatabaseProductName());
System.out.println(
"数据库版本: "
+ dMetaData.getDatabaseProductVersion());
ResultSet resultSet = dMetaData.getPrimaryKeys(
null
,
null
,
"users"
);
while
(resultSet.next()) {
System.out.println(
"表类别:"
+ resultSet.getString(
1
));
System.out.println(
"表模式:"
+ resultSet.getString(
2
));
System.out.println(
"表名称:"
+ resultSet.getString(
3
));
System.out.println(
"列名称:"
+ resultSet.getString(
4
));
System.out.println(
"主键:"
+ resultSet.getString(
5
));
System.out.println(
"主键名称:"
+ resultSet.getString(
6
));
}
}
catch
(SQLException e) {
e.printStackTrace();
}
}
}
|
输出:
1
2
3
4
5
6
7
8
|
数据库名:MySQL
数据库版本: 5.5.19
表类别:jdbcdemo
表模式:null
表名称:users
列名称:id
主键:1
主键名称:PRIMARY
|
(2)ResultSetMetaData:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package
javase.jdbc;
import
java.sql.Connection;
import
java.sql.PreparedStatement;
import
java.sql.ResultSetMetaData;
import
java.sql.SQLException;
public
class
ResultSetMetaDataDemo {
public
static
void
main(String[] args) {
String sql =
"SELECT id,username,password,classId FROM users"
;
Connection connection = JDBCConnection.getConnection();
try
{
PreparedStatement pStatement = connection.prepareStatement(sql);
ResultSetMetaData rSetMetaData = pStatement.getMetaData();
System.out.println(
"返回数据有"
+ rSetMetaData.getColumnCount() +
"个字段"
);
if
(rSetMetaData.isAutoIncrement(
1
))
System.out.println(rSetMetaData.getColumnName(
1
) +
"字段是自增的"
);
}
catch
(SQLException e) {
e.printStackTrace();
}
}
}
|
输出:
1
2
|
返回数据有4个字段
id字段是自增的
|
本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1767351,如需转载请自行联系原作者