diff --git "a/25 \346\234\261\346\203\240\345\277\240/20230520 jsp\344\275\234\344\270\232.md" "b/25 \346\234\261\346\203\240\345\277\240/20230520 jsp\344\275\234\344\270\232.md" new file mode 100644 index 0000000000000000000000000000000000000000..7c9844269be50db9056c3abb20a13e4890090186 --- /dev/null +++ "b/25 \346\234\261\346\203\240\345\277\240/20230520 jsp\344\275\234\344\270\232.md" @@ -0,0 +1,99 @@ +```java + +import java.sql.*; + +public class Jdbc { + private Connection conn() { + try { + Class.forName("com.mysql.jdbc.Driver"); + String url = "jdbc:mysql://localhost:3306/student_db?useSSL=false&useUnicode=true&characterEchoing=utf8"; + Connection conn = DriverManager.getConnection(url, "root", "root"); + return conn; + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + //查询 + ResultSet select(String sql){ + try { + PreparedStatement pst = conn().prepareStatement(sql); + ResultSet re = pst.executeQuery(); + return re; + } catch (SQLException e) { + throw new RuntimeException(e); + } + } +} + +//学生对象 +public class Student { + private int id; + private String name; + private String sex; + + public Student() { + } + + public Student(int id, String name, String sex) { + this.id = id; + this.name = name; + this.sex = sex; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } +} + +import java.sql.*; +import java.util.ArrayList; + //测试 +public class Test { + public static void main(String[] args) { + Jdbc jdbc = new Jdbc(); + ResultSet re = jdbc.select("select * from student"); + ArrayList stu = new ArrayList<>(); + try { + while (re.next()) { + int id = re.getInt(1); + String name = re.getString(2); + String sex = re.getString(3); + Student s = new Student(id, name, sex); + stu.add(s); + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + + System.out.println("ID\t\t姓名\t\t性别"); + for (int i = 0; i < stu.size(); i++) { + Student s = stu.get(i); + System.out.println(s.getId()+"\t\t"+s.getName()+"\t\t"+s.getSex()); + } + } +} +``` +