From 986048006680a6ecc88ba9fd7e474f7d2cf677a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E6=AD=A3=E7=84=95?= <1953038944@qq.com> Date: Thu, 25 May 2023 23:34:22 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E6=AC=A1=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...a-\346\225\260\346\215\256\345\272\223.md" | 238 ++++++++++++++++++ 1 file changed, 238 insertions(+) create mode 100644 "38 \351\273\204\346\255\243\347\204\225/20230524 \347\275\221\351\241\265-java-\346\225\260\346\215\256\345\272\223.md" diff --git "a/38 \351\273\204\346\255\243\347\204\225/20230524 \347\275\221\351\241\265-java-\346\225\260\346\215\256\345\272\223.md" "b/38 \351\273\204\346\255\243\347\204\225/20230524 \347\275\221\351\241\265-java-\346\225\260\346\215\256\345\272\223.md" new file mode 100644 index 0000000..2478f70 --- /dev/null +++ "b/38 \351\273\204\346\255\243\347\204\225/20230524 \347\275\221\351\241\265-java-\346\225\260\346\215\256\345\272\223.md" @@ -0,0 +1,238 @@ +```mysql +create database student_db character set utf8; +use student_db; +create table student( +stuid int, +stuname varchar(10), +stusex varchar(2) +); +insert into student values(1,"张三","男"); +insert into student values(2,"李四","女"); +insert into student values(3,"王五","男"); +``` + +```java +//工具类 +import java.sql.*; + +public class JDBCUtil { + 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 = ""; + //注册驱动的方法 + //用静态代码块,注册驱动,{}表示代码块,static表示静态的,最先执行 + 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; + } + + /** + * 通用的query + * @param sql 接收的SQL语句 + * @return 将查询的结果集返回给调用者 + */ + public static ResultSet query(String sql,String ...keys) throws SQLException { + Connection conn = getConn(); + PreparedStatement pst = conn.prepareStatement(sql); + for (int i = 0; i < keys.length; i++) { + pst.setString(i+1,keys[i]); + } + ResultSet rst = pst.executeQuery(); + return rst; + + } + + + + //通用的update + public static int update(String sql,String ...keys) throws SQLException { + Connection conn = getConn(); + PreparedStatement pst = conn.prepareStatement(sql); + for (int i = 0; i < keys.length; i++) { + pst.setString(i+1,keys[i]); + } + int i = pst.executeUpdate(); + return i; + + } + + //通用的释放资源的方法 + public static void close(Connection conn,PreparedStatement pst,ResultSet rst){ + try { + if (rst!=null){ + rst.close(); + } + if (pst!=null){ + rst.close(); + } + if (conn!=null){ + rst.close(); + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + } +} + +``` + +```java + + + +
+ +