JDBC如何与数据库连接获取数据(原理+代码)

论坛 期权论坛 脚本     
匿名技术用户   2020-12-27 20:11   11   0

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();
}
}
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP