虽然在平时的开发过程中我们不会直接使JDBC的API来操作数据库,但是JDBC是大多数ORM框架的基础。只有掌握了JDBC的使用才能更好的掌握ORM框架。本篇博客就对JDBC做下介绍,以及使用JDBC操作数据库的一般流程。
JDBC(Java数据库连接)是Sun公司提供的一组操作数据库的接口。各个数据库厂商提供具体的数据库驱动实现类。开发者就可以通过统一的JDBC API来访问各类数据库了。JDBC可以帮我们完成下面三件事:
public static Connection getConnection(String url,
String user, String password) throws SQLException
//返回一个Statement对象
Statement createStatement() throws SQLException;
//返回一个预编译的Statement对象,也就是先将Sql语句提交到数据库进行预编译
PreparedStatement prepareStatement(String sql) throws SQLException;
//该对象用于调用存储过程
CallableStatement prepareCall(String sql) throws SQLException;
另外Connection对象还提供了如下对象来对事务进行操作:
//设置回滚点
Savepoint setSavepoint() throws SQLException;
Savepoint setSavepoint(String name) throws SQLException;
//设置隔离级别
void setTransactionIsolation(int level) throws SQLException;
//设置回滚点
void rollback() throws SQLException;
void rollback(Savepoint savepoint) throws SQLException;
void setAutoCommit(boolean autoCommit) throws SQLException;
//提交事务
void commit();
//执行查询SQL,并返回结果集
ResultSet executeQuery(String sql) throws SQLException;
//执行DML,并返回影响的条数,也可以执行DDL,返回0
int executeUpdate(String sql) throws SQLException;
//可以执行所有SQL,如果SQL是查询语句并能查到结果返回true,否则返回false
boolean execute(String sql) throws SQLException;
/**
* step1:加载驱动;
* step2:获得连接;
* step3:创建Statement;
* step4:执行语句,获取结果集;
* step5:处理结果集;
* step6:关闭资源(ResultSet、Statement和Connection)
*/
//开启事务
setAutoCommit(fasle);
//遇到异常回滚
//提交事务
commit();
每次创建数据库的连接是比较耗费资源的,所以将数据库连接资源缓存起来,重复利用。
下面是一个最简单的JDBC列子代码,是一个最典型的JDBC查询过程。
public class JDBCUtil {
public static final Logger log = LoggerFactory.getLogger(JDBCUtil.class);
public static final String URL = "jdbc:mysql://127.0.0.1/mysql";
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String USERNAME = "root";
public static final String PASSWORD = "root";
private Connection getConnection(){
Connection conn = null;
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
} catch (ClassNotFoundException e) {
log.error("get connection exception",e);
}catch (SQLException e) {
log.error("get connection exception",e);
}
return conn;
}
public void queryAndEchoUser(String userName){
String sql = "select * from user where user = ?";
Connection connection = getConnection();
PreparedStatement preparedStatement;
ResultSet resultSet=null;
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"root");
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
log.info("host-->"+resultSet.getString(1));
}
} catch (SQLException e) {
//
}finally {
//close resultSet
//close preparedStatement
//close connection
}
}
}
上面的代码略微显得复杂,特别是将查出来的结果集转换为Bean对象,关闭资源那块。使用Apache提供的工具类能适当减少这样的模板代码:
public class DbUtilsUseBeanMySQL {
public static void main(String[] args) {
Connection conn = null;
String jdbcURL = "jdbc:mysql://localhost/octopus";
String jdbcDriver = "com.mysql.jdbc.Driver";
String user = "root";
String password = "root";
try {
DbUtils.loadDriver(jdbcDriver);
conn = DriverManager.getConnection(jdbcURL, user, password);
QueryRunner qRunner = new QueryRunner();
List beans = (List) qRunner.query(conn, "select id, name from animals_table",
new BeanListHandler(Employee.class));
for (int i = 0; i < beans.size(); i++) {
Employee bean = (Employee) beans.get(i);
bean.print();
}
} catch (SQLException e) {
// handle the exception
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
}
当然以上只是DbUtil最简单的使用,这个工具还支持数据源,事务管理等高级特性,需要的时候可以查询API使用。
原文:https://www.cnblogs.com/54chensongxia/p/11427136.html