导入驱动包,加载具体的驱动类
Class.forName(“具体驱动类”)
与数据库建立连接
connection=DriverManager.getConnection();
通过connection,获取操作数据库的对象(Statement/prepareStatement/callablestatement)
stmt=(Statement) connection.createStatement();
查询处理结果集
rs=(ResultSet) pstmt.executeQuery();
while(rs.next()){rs.getxxx(…);}
catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
finally{
//打开的顺序与关闭的顺序相反,后打开的先关闭,类似于栈
if(rs!=null)rs.close(); //先排空,再关闭
if(stmt!=null)stmt.close();
if(connection!=null)connection.close();
}
jdbc中,除了Class.forName()抛出ClassNotFoundException,其余的方法都是抛出SQLException
callablestatement:调用存储过程、存储函数
connection.prepareCall(参数;存储过程或存储函数名)
参数格式
存储过程://无返回值,用out参数来代替
{call 存储过程名(参数列表)}
存储函数//有返回值return
{?=call 存储函数名(参数表)}