From 8454aef0594f824d8f24b186ca93ca3b68fbe134 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 21 May 2023 22:56:44 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../20230521 \344\275\234\344\270\232.txt" | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 "43 \345\272\236\346\200\235\350\277\234/20230521 \344\275\234\344\270\232.txt" diff --git "a/43 \345\272\236\346\200\235\350\277\234/20230521 \344\275\234\344\270\232.txt" "b/43 \345\272\236\346\200\235\350\277\234/20230521 \344\275\234\344\270\232.txt" new file mode 100644 index 0000000..b16895f --- /dev/null +++ "b/43 \345\272\236\346\200\235\350\277\234/20230521 \344\275\234\344\270\232.txt" @@ -0,0 +1,98 @@ +```java +public class Student { + private int id; + private String name; + private String sex; + + public Student(int id, String name, String sex) { + this.id = id; + this.name = name; + this.sex = sex; + } + + public Student() { + } + + 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; + } + + @Override + public String toString() { + return "Student{" + + "id=" + id + + ", name='" + name + '\'' + + ", sex='" + sex + '\'' + + '}'; + } +} +import java.sql.*; +import java.util.ArrayList; + +public class DBUtil { + 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("jdbc:mysql://localhost:3306/student_db?useSSL=false&useUnicode=true&character=utf8", "root", "122319"); + return conn; + } + public static ResultSet Query(String sql,String ...keys) throws SQLException { + Connection conn = getConn(); + PreparedStatement pre = conn.prepareStatement(sql); + for (int i = 0; i < keys.length; i++) { + pre.setString((i+1),keys[i]); + } + ResultSet res = pre.executeQuery(); + return res; + } + public static void close(Connection con,PreparedStatement pre,ResultSet res) throws SQLException { + if(res!=null){ + res.close(); + }if(pre!=null){ + pre.close(); + }if(con!=null){ + con.close(); + } + } +} +class Test{ + public static void main(String[] args) throws SQLException { + String sql="select * from student"; + ResultSet res = DBUtil.Query(sql); + ArrayList list = new ArrayList<>(); + while (res.next()){ + list.add(new Student(res.getInt(1),res.getString(2),res.getString(3))); + } + for (int i = 0; i < list.size(); i++) { + Student student = list.get(i); + System.out.println(student); + } + DBUtil.close(null,null,res); + } +} +``` \ No newline at end of file -- Gitee