JDBC

[复制链接]
发表于 2023-1-10 22:40:13 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
JDBC

JDBC六步


  • 注册驱动
  • 建立连接
  • 获取预编译的数据库操作对象
  • 执行SQL
  • 处理查询结果
  • 释放资源
  1. Connection conn = null;
  2. PrepareStatement ps = null;
  3. ResultSet rs = null;
  4. String url="jdbc:mysql://数据库地址:端口号/数据库名称";
  5. String user="用户名";
  6. String pwd="密码";
  7. try{
  8.     //注册驱动
  9.         Class.forname("com.mysql.cj.jdbc.Driver")
  10.         //建立连接
  11.         conn = DriverManager.getConnection(url,user,pwd);
  12.         //获取预编译的数据库操作对象
  13.         String SQL="select * from table";
  14.         ps = conn.PrepareStatement(SQL);
  15.         //执行SQL
  16.         rs = ps.executeQuery();
  17.         //处理查询结果
  18.         while(rs.next()){
  19.             String name = rs.getString("name");
  20.         }
  21. }catch(Exception e){
  22.     e.printStackTrace()
  23. }finally{
  24.     //释放资源
  25.     if(rs!=null){
  26.         try{
  27.             rs.close();
  28.         }catch(Exception e){
  29.                     e.printStackTrace()
  30.                 }
  31.     }
  32.     if(ps!=null){
  33.         try{
  34.             ps.close();
  35.         }catch(Exception e){
  36.                     e.printStackTrace()
  37.                 }
  38.     }
  39.     if(conn!=null){
  40.         try{
  41.             conn.close();
  42.         }catch(Exception e){
  43.                     e.printStackTrace()
  44.                 }
  45.     }
  46. }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表