From d146a3910c1859fd9a6cff0340e3365183c3cab0 Mon Sep 17 00:00:00 2001 From: xcchengguo <2395432766@qq.com> Date: Sun, 21 May 2023 23:43:28 +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.md" | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 "18 \350\260\242\345\256\270/20230521 \344\275\234\344\270\232.md" diff --git "a/18 \350\260\242\345\256\270/20230521 \344\275\234\344\270\232.md" "b/18 \350\260\242\345\256\270/20230521 \344\275\234\344\270\232.md" new file mode 100644 index 0000000..49fd21a --- /dev/null +++ "b/18 \350\260\242\345\256\270/20230521 \344\275\234\344\270\232.md" @@ -0,0 +1,62 @@ +~~~java +import java.sql.*; +import java.util.ArrayList; + +public class Gongju { + 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", "root"); + 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]); + 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(); + } + } +} +~~~ + +~~~java +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; + +public class Testi { + static class test{ + public static void main(String[] args) throws SQLException { + String sql="select * from student"; + ResultSet res = Gongju.Query(sql); + ArrayList list = new ArrayList<>(); + while (res.next()){ + list.add(new Studenti(res.getString(1),res.getString(2),res.getString(3))); + } + for (int i = 0; i < list.size(); i++) { + Studenti student = list.get(i); + System.out.println(student); + } + Gongju.close(null,null,res); + } + } +} +~~~ + -- Gitee