判断数据库是否支持事务
try {
DatabaseMetaData dmd = connection.getMetaData();
if (dmd.supportsTransactions()) {
// Transactions are supported
} else {
// Transactions are not supported
}
} catch (SQLException e) {
}
处理SQL异常
下例说明了如何取出SQL异常信息
This example demonstrates how to retrieve the information in a
SQLException.
try {
// Execute SQL statements...
} catch (SQLException e) {
while (e != null) {
// 取出表示异常原因的可读信息 Retrieve a human-readable message identifying
// the reason for the exception
String message = e.getMessage();
// This vendor-independent string contains a code that identifies
// the reason for the exception.
// The code follows the Open Group SQL conventions.
String sqlState = e.getSQLState();
// Retrieve a vendor-specific code identifying the reason for the exception.
int errorCode = e.getErrorCode();
// If it is necessary to execute code based on this error code,
// you should ensure that the expected driver is being
// used before using the error code.
// Get driver name
String driverName = connection.getMetaData().getDriverName();
if (driverName.equals("Oracle JDBC Driver") && errorCode == 123) {
// Process error...
}
// 取得下一个异常 The exception may have been chained; process the next chained exception
e = e.getNextException();
}
}
设定从数据库取出的记录数
取出的固定大小可以用于statement上,这样取出的结果集都是一样的大小;
固定大小也可用于ResultSet上,这样下次的记录数就是设定的大小.
以下是使用的例子
try {
// Get the fetch size of a statement
Statement stmt = connection.createStatement ();
int fetchSize = stmt.getFetchSize();
// Set the fetch size on the statement
stmt.setFetchSize(100);
// Create a result set
ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");
// Change the fetch size on the result set
resultSet.setFetchSize(100);
} catch (SQLException e) {
}
取得结果集的列名
try {
// Create a result set
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM my_table");
// Get result set meta data
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
// 取得列名,字段序列默认从一开始 Get the column names; column indices start from 1
for (int i=1; i<numColumns+1; i++) {
String columnName = rsmd.getColumnName(i);
// Get the name of the column's table name
String tableName = rsmd.getTableName(i);
}
} catch (SQLException e) {
}
