Jdbc - Some APIs
some api
表结构、列信息获取
try (Connection connection = DriverManager.getConnection("");
PreparedStatement preparedStatement = connection.prepareStatement("select * from table where 1=2")) {
final ResultSetMetaData metaData = preparedStatement.getMetaData();
int columnCount = metaData.getColumnCount();
IntStream.rangeClosed(1, columnCount).forEach(i -> {
try {
String colName = metaData.getColumnName(i);
String colTypeName = metaData.getColumnTypeName(i);
int colType = metaData.getColumnType(i);
metaData.getPrecision(i);
metaData.getScale(i);
metaData.isAutoIncrement(i);
metaData.isDefinitelyWritable(i);
metaData.isReadOnly(i);
metaData.isWritable(i);
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
} catch (SQLException e) {
throw new RuntimeException(e);
}
查询
try (Connection connection = DriverManager.getConnection("");
PreparedStatement statement = connection.prepareStatement("");
ResultSet rs = statement.executeQuery()) {
int colCount = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 0; i < colCount; i++) {
final int type = rs.getMetaData().getColumnType(i);
switch (type) {
case Types.VARBINARY: {
}
break;
case Types.INTEGER: {
}
break;
default: {
}
break;
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
事务
Connection connection = DriverManager.getConnection("");
try (connection;
PreparedStatement statement = connection.prepareStatement("");) {
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
statement.executeUpdate();
connection.commit();
} catch (Exception e) {
connection.rollback();
e.printStackTrace();
} finally {
connection.setAutoCommit(true);
}