传统jdbc连接代码

public Role getRole(Long id) {
Role role = null ;
//声明JDBC 变量
Connection con = null ;
PreparedStatement ps = null;
ResultSet rs = null ;
try {
//注册驱动程序
Class . forName (” com.mysql.jdbc.Driver”);
//获取连接
con = DriverManager . getConnection (” jdbc:mysql://localhost:
3306/chapter12 ” ,
” root ”,”123456” ) ;
//预编译SQL
ps = con. prepareStatement ( ” select Id , role name , note from t_role
where id = ?” ) ;
//设置参数
ps.setLong(l , id) ;
//执行SQL
rs= ps . executeQuery() ;
//组装结果集返回POJO
while (rs . next () ) {
role =new Role();
role.setid(rs.getLong(l)) ;
role . setRoleName(rs . getString(2));
role . setNote(rs . getString(3)) ;
} catch (ClassNotFoundException I SQLException e) {
//异常处理
e. printStackTrace () ;
} finally {
//关闭数据库连接资源
try {
if (rs != null && !rs.isClosed( ) ) {
rs. close() ;
} catch (SQLException e ) {
e.printStackTrace ( ) ;
try {
if (ps ! = null && ! ps. isClosed ()) {
ps . close() ;
} catch (SQLException e) {
e . printStackTrace();
try {
if (con ! = null & & ! con . isClosed () ) {
con . close();
} catch (SQLException e) {
e.printStackTrace() ;
}

你可能感兴趣的:(java)