用java的语法糖写的jdbc(try... with..source)

mac2024-03-20  28

看看写代码有语法糖和没语法糖的区别(这里我说明一下,我数据库是8.0以上的,连接时的url跟5.0版本有一些区别) 先看一般写法:

static String url = "jdbc:mysql://localhost:3306/student?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true "; static String username = "root"; static String pwd = ""; public static void query() {//查询 Connection conn = null;加 PreparedStatement pstmt=null; ResultSet rs = null; try { //1,导入驱动,加载具体驱动类 Class.forName("com.mysql.cj.jdbc.Driver"); //2,与数据库连接 conn = DriverManager.getConnection(url, username, pwd); //发送sql,执行增删改查 String sql ="select count(*) from user where id= ?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,"亮"); rs=pstmt.executeQuery(); System.out.println(rs); }catch (SQLException e){ e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { if(rs!=null) rs.close(); if(pstmt!=null) pstmt.close();// 对象.方法 if(conn!=null)conn.close(); }catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); } } }

看到上面的代码是不是觉得很繁琐,下面看看用了语法糖的写法

`//语法糖

//语法糖 public static void queryw() { String sql = "select count(*) from user where id= ?"; try (Connection conn = DriverManager.getConnection(url, username, pwd);//分号隔开 PreparedStatement pstmt = conn.prepareStatement(sql)){ pstmt.setInt(1, 1); try (ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { System.out.println(rs); } } }catch(SQLException e){ e.printStackTrace(); } }

` 相比之下,有了语法糖,代码是不是简洁了许多!

最新回复(0)