diff --git "a/08 \350\224\241\346\263\275\351\222\246/20230520 \351\233\206\345\220\210JSP.md" "b/08 \350\224\241\346\263\275\351\222\246/20230520 \351\233\206\345\220\210JSP.md" new file mode 100644 index 0000000000000000000000000000000000000000..c6665c202da7ed631c42a369754adb5861e6c9d9 --- /dev/null +++ "b/08 \350\224\241\346\263\275\351\222\246/20230520 \351\233\206\345\220\210JSP.md" @@ -0,0 +1,107 @@ +## 工具类 + +~~~java +import java.sql.*; +public class DBUtil { + private static final String url= "jdbc:mysql://localhost:3306/student_db?useSSL=false&useUnicode=true&characterEncoding=utf8"; + private static final String username="root"; + private static final String password="root"; + static { + try { + Class.forName("com.mysql.jdbc.Driver"); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + + } + public static Connection getConn() throws SQLException { + Connection conn = DriverManager.getConnection(url,username,password); + return conn; + } + //查询 + public static ResultSet query(String sql) throws SQLException { + Connection conn = getConn(); + PreparedStatement pst = conn.prepareStatement(sql); + ResultSet rs = pst.executeQuery(); + return rs; + } + //释放资源 + public static void close(Connection conn,PreparedStatement pst,ResultSet rs) throws SQLException { + if (rs!=null){ + rs.close(); + } + if (pst!=null){ + pst.close(); + } + if (conn!=null){ + conn.close(); + } +~~~ + +## 测试类 + +~~~java +import java.sql.*; +import java.util.ArrayList; + +public class Test02 { + public static void main(String[] args) throws SQLException { + ArrayList stu = new ArrayList<>(); + String sql = "select * from student"; + ResultSet rs = DBUtil.query(sql); + while (rs.next()){ + int id = rs.getInt("id"); + String name = rs.getString("name"); + String sex = rs.getString("sex"); + student st1 = new student(id, name, sex); + stu.add(st1); + } + for (int i = 0; i