网上读了几篇关于这方面的文章,这里就把自己理解的写下来,这个在项目中不会用到,但在面试或者对于理解关于JAVA ORM 框架这一块也许会有帮助吧。
JDBC连接数据库大体分为以下几个步骤:
- 加载JDBC的驱动程序: 加载相应的数据库驱动到JVM
try{
//加载相应的database驱动程序
//Class.forName()是java.lang.Class的静态方法
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
e.printStackTrace();
}
- 创建数据库的连接
在上一步中加载了DataBase的Driver,之后利用 DriverManager的静态方法getConnection(…)获得连接Connection。
//Connection 代表数据库的连接
//url代表连接数据库时的协议:子协议:数据源标识
String url = "jdbc:mysql://localhost:3306/mytable";
//数据库账号
Stirng userName = "root";
//数据库密码
String password = "123";
try{
Connection con =
DriverManager.getConnection(url, userName, password);
}catch(Exception e){
e.printStackTrace();
}
- 创建Statement对象,具体分为三类,需要根据项目需要采用不同
静态SQL语句:Statement
动态SQL语句:PreparedStatement
存储过程:CallableStatement
Statement stmt = con.createStatement();
PreparedStatement stmt = con.prepareStatement(sql);
CallableStatement stmt =
con.prepareCall("CALL demoSp(?,?)}";
- 执行SQL语句
Statement主要提供了以下三种类型的方法:
//执行查询
ResultSet executeQuery(String sql);
//执行增删改等
int executeUpdate(String sql);
//返回多个结果集
boolean execute(String sql);
//对结果集的访问
while(result.next()){
String user = result.getString("user");
...
}
- 操作完成,关闭连接
需要按照操作顺序来依次关闭。
if(result != null){
result.close();//关闭记录集
}
if(statement!= null){
statement.close();//关闭statement
}
if(con!= null){
con.close();//关闭连接
}