From e8c2e04e7a8984305de8a03539ec36ac8e962b9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?5=E5=8F=B7=E6=9E=97=E4=BC=9F=E5=BD=AC?= <2401916501@qq.com> Date: Sun, 21 May 2023 23:54:27 +0800 Subject: [PATCH] zuoye --- .../20230520 \344\275\234\344\270\232.md" | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 "05 \346\236\227\344\274\237\345\275\254/20230520 \344\275\234\344\270\232.md" diff --git "a/05 \346\236\227\344\274\237\345\275\254/20230520 \344\275\234\344\270\232.md" "b/05 \346\236\227\344\274\237\345\275\254/20230520 \344\275\234\344\270\232.md" new file mode 100644 index 0000000..1bd9f2b --- /dev/null +++ "b/05 \346\236\227\344\274\237\345\275\254/20230520 \344\275\234\344\270\232.md" @@ -0,0 +1,116 @@ +# 作业 + +```java +//JDBC工具类 +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); + } + } +} +``` + + + +```Java +//学生对象 +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; + } + +} +``` + + + +```java + + +//测试类 +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()); + } + } +} + + +``` + -- Gitee