JDBC与数据库连接主要分以下几个步骤:
1.加载驱动程序
2.创建Connection连接对象
3. 创建预编译的sql语句块对象
4.通过语句块对象调用其相应方法去执行相应的sql语句,并返回结果集
5.关闭预编译sql对象关闭数据库连接
例:jdbc连接mysql/oracle数据库,并进行查询的典型代码:
public static void jdbcTest(){ Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc://mysql:localhost:3306/myhib", "root", "1234"); ps=conn.prepareStatement("select id,name from t_user where id=?"); ps.setInt(1, 20); rs=ps.executeQuery(); } catch (Exception e) { e.printStackTrace(); }finally{ try { if(rs!=null){ rs.close();
} } catch (SQLException e) { e.printStackTrace(); } try { if(ps!=null){ ps.close();
} } catch (SQLException e) { e.printStackTrace(); } try { if(conn!=null){ conn.close();
} } catch (SQLException e) { e.printStackTrace(); } } }
|