本文知识点(目录):
1、什么是jdbc
2、jdbc接口的核心API
3、使用JDBC技术连接MySQL数据库的方法
4、使用Statement执行sql语句(DDL、DML、DQL)
5、使用PreparedStatement执行sql语句
6、使用callablestaement执行sql语句,调用存储过程
7、附录(jdbc连接数据库 实操)
8、完整的JDBC封装过程,及调用jdbc的使用过程实例
1、什么是jdbc
简单的讲就是:使用java代码(程序)发送sql语句的技术,称为jdbc技术。
2、jdbc接口的核心API
1 |-Driver 接口:表示java驱动程序接口。所有的具体的数据库厂商要实现的接口. 2 |-connect(String url, Properties info):连接数据库的方法 3 Url:连接数据库的URL 4 URL语法:jdbc协议:数据库子协议://主机:端口/数据库名 5 User:数据库的用户名 6 Password:数据的用户密码 7 |-DriverManager 类:驱动管理器类,用于管理所有的注册的驱动程序 8 |-registerDriver(Driver driver):注册驱动类对象 9 |-getConnection(String url, String user, String password):获取连接对象 10 |-Connection 接口:表示java程序和数据库的连接对象 11 |-createStatement() 12 |-prepareStatement(String sql):创建PreparedStatement对象 13 |-prepareCall(String sql):创建CallableStatement对象 14 |-statement 接口:用于执行静态的sql语句 15 |-executeUpdate(String sql): 执行静态的sql语句(DDL、DML) 16 |-executeQuery(String sql) :静态的查询sql语句(DQL) 17 |-PreparedStatement 接口:用于执行预编译sql语句 18 |-executeUpdate(String sql):执行静态的sql语句(DDL、DML) 19 |-executeQuery(String sql):静态的查询sql语句(DQL) 20 |-CallableStatement 接口:用于执行存储过程的sql语句(call xxx) 21 |-ResultSet 接口:用于封装查询出来的数据 22 |-next():将光标移到下一行 23 |-getxxx(int columnIndex):获取列的值(有getInt()、getString()、getArray()、getURL() 等等)
24 |-getRow():获取当前行编号。
3、使用JDBC技术连接MySQL数据库的方法
1 package com.shore.a_jdbc; 2 3 import java.sql.Connection; 4 import java.sql.Driver; 5 import java.sql.DriverManager; 6 import java.util.Properties; 7 8 /** 9 * @author DSHORE/2019-3-23 10 * 11 */ 12 //连接MySQL数据库的几种方法 13 public class connJDBC { 14 // jdbc协议:数据库的子协议:主机:端口/要连接的数据库名称 15 private String url = "jdbc:mysql://localhost:3306/school";//连接数据库的URL链接 16 private String user = "root";//用户名 17 private String password = "123456";//密码 18 /* 19 * 第一种方法: 20 * */ 21 public void test1() throws Exception{ 22 //1.创建驱动程序类对象 23 Driver driver = new com.mysql.jdbc.Driver(); 24 //Driver driver = new org.gjt.mm.mysql.Driver();//旧版本的创建方法 25 //设置用户名密码 26 Properties props = new Properties(); 27 props.setProperty("user",user); 28 props.setProperty("password",password); 29 //2.连接数据库,返回连接对象 30 Connection conn = driver.connect(url, props); 31 System.out.println(conn);//返回值:com.mysql.jdbc.JDBC4Connection@29c56c60,表示已连接成功 32 } 33 /* 34 * 第二种方法:使用驱动管理器类连接数据库 35 * */ 36 public void test2()throws Exception{ 37 //1.创建驱动程序类对象 38 Driver driver = new com.mysql.jdbc.Driver();//MySQL数据库 39 //Driver driver2 = new com.oracle.jdbc.Driver();//Oracle数据库 40 //注册驱动程序(可以注册多个驱动) 41 DriverManager.registerDriver(driver); 42 //DriverManager.registerDriver(driver2); 43 //2.连接数据库 44 Connection conn=DriverManager.getConnection(url, user, password); 45 System.out.println(conn); 46 } 47 /* 48 * 第三种方法:使用加载驱动程序类 来注册 驱动程序。(推荐使用这种方式连接数据库) 49 * */ 50 public void test3() throws Exception{ 51 //通过得到字节码对象的方式加载静态代码块,从而注册驱动 52 Class.forName("com.mysql.jdbc.Driver"); 53 //2.连接数据库 54 Connection conn = DriverManager.getConnection(url, user, password); 55 System.out.println(conn); 56 } 57 }
4、使用Statement执行sql语句
4.1、执行DDL语句
1 package com.shore.b_statement; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6 import java.sql.Statement; 7 8 import org.junit.Test; 9 /* 10 *使用statement对象执行静态sql语句(创建表) 11 **/ 12 public class Demo1 { 13 //连接数据库的URL 14 private String url="jdbc:mysql://localhost:3306/school"; 15 //jdbc协议:数据库的子协议:主机:端口/连接的数据库 16 private String user="root";//用户名 17 private String password="123456";//密码 18 19 //执行DDL语句 20 @Test 21 public void test1(){ 22 Statement statement = null; 23 Connection connection = null; 24 try { 25 //1.注册驱动 26 Class.forName("com.mysql.jdbc.Driver"); 27 //2.获取连接对象 28 connection = DriverManager.getConnection(url, user, password); 29 //3.创建statement 30 statement = connection.createStatement(); 31 //4.准备sql语句 32 String sql = "CREATE TABLE student(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(32),sex VARCHAR(2));";//创建表 33 int count = statement.executeUpdate(sql); 34 System.out.println("影响行数:"+count+"行!"); 35 } catch (ClassNotFoundException e) { 36 e.printStackTrace(); 37 } catch (SQLException e) { 38 e.printStackTrace(); 39 }finally{ 40 //5.关闭连接(顺序:后代开的先关闭) 41 try { 42 if(statement != null) statement.close(); 43 if(connection != null) connection.close(); 44 } catch (SQLException e) { 45 e.printStackTrace(); 46 } 47 } 48 } 49 }
4.2、执行DML语句
封装工具类(JdbcUtil.java) 文件。(由于连接数据库和关闭资源的那部分代码是不变的,所以将他们封装起来,用到时 就直接调用即可)
1 package com.shore.util; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.sql.Connection; 7 import java.sql.DriverManager; 8 import java.sql.ResultSet; 9 import java.sql.SQLException; 10 import java.sql.Statement; 11 import java.util.Properties; 12 13 public class JdbcUtil { //把固定不变的那部分代码封装起来 14 //动态连接数据 15 private static String url = null; 16 private static String user = null;//用户名 17 private static String password = null;//密码 18 private static String driverClass = null; 19 //静态代码块中(只加载一次) 20 static{ 21 //读取db.properties 22 Properties props = new Properties(); 23 try { 24 FileInputStream fis = new FileInputStream("./src/db.properties"); 25 //加载文件 26 props.load(fis); 27 url = props.getProperty("url"); 28 user = props.getProperty("user"); 29 password = props.getProperty("password"); 30 driverClass = props.getProperty("driverClass"); 31 //注册驱动 32 Class.forName(driverClass); 33 } catch (FileNotFoundException e) { 34 e.printStackTrace(); 35 } catch (IOException e) { 36 e.printStackTrace(); 37 } catch (ClassNotFoundException e) { 38 e.printStackTrace(); 39 System.out.println("注册驱动失败"); 40 } 41 } 42 //获取连接 43 public static Connection getConnection(){ 44 try { 45 Connection conn = DriverManager.getConnection(url, user, password); 46 return conn; 47 } catch (SQLException e) { 48 e.printStackTrace(); 49 throw new RuntimeException(); 50 } 51 } 52 //释放资源 53 public static void close(Connection conn,Statement stmt,ResultSet rs){ 54 try { 55 if(stmt != null) stmt.close(); 56 if(conn != null) conn.close(); 57 if(rs != null) rs.close(); 58 } catch (SQLException e) { 59 e.printStackTrace(); 60 } 61 } 62 }
db.properties配置文件(存储数据库链接、用户及密码等)
1 url = jdbc:mysql://localhost:3306/school //把数据库的链接入口配置在一个文件中,方便以后操作(更改账号密码等等) 2 user = root 3 password = 123456 4 driverClass = com.mysql.jdbc.Driver
执行DML语句 正文
1 package com.shore.b_statement; 2 3 import java.sql.Connection; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 import java.sql.Statement; 7 8 import org.junit.Test; 9 10 import com.bw.util.JdbcUtil; 11 12 /** 13 * 使用statement执行DML语句(添加、删除、修改数据) 14 * 15 */ 16 public class Demo2 { 17 /* 18 * 向student表中添加数据 19 * */ 20 @Test 21 public void testInsert(){ 22 ResultSet rs = null; 23 Connection conn = null; 24 Statement stmt = null; 25 //通过工具类获取;连接对象 26 conn = JdbcUtil.getConnection(); 27 //常见statement对象 28 try { 29 stmt=conn.createStatement(); 30 } catch (SQLException e) { 31 e.printStackTrace(); 32 } 33 String sql = "INSERT INTO student(NAME,sex) VALUES('张三','女');"; 34 try { 35 int count = stmt.executeUpdate(sql); 36 System.out.println(count); 37 } catch (SQLException e) { 38 e.printStackTrace(); 39 } 40 JdbcUtil.close(conn,stmt,rs); 41 } 42 /* 43 * 修改student表中的数据 44 * */ 45 @Test 46 public void testUpdate(){ 47 ResultSet rs = null; 48 Connection conn =null; 49 Statement stmt = null; 50 //通过工具类获取;连接对象 51 conn = JdbcUtil.getConnection(); 52 //常见statement对象 53 try { 54 stmt = conn.createStatement(); 55 } catch (SQLException e) { 56 e.printStackTrace(); 57 } 58 String sql = "UPDATE student SET NAME = '王五' WHERE id = 1;"; 59 try { 60 int count=stmt.executeUpdate(sql); 61 System.out.println(count); 62 } catch (SQLException e) { 63 e.printStackTrace(); 64 } 65 JdbcUtil.close(conn,stmt,rs); 66 } 67 /* 68 * 删除student表中的数据 69 * */ 70 @Test 71 public void testDelete(){ 72 ResultSet rs = null; 73 Connection conn = null; 74 Statement stmt = null; 75 //通过工具类获取;连接对象 76 conn = JdbcUtil.getConnection(); 77 //常见statement对象 78 try { 79 stmt = conn.createStatement(); 80 } catch (SQLException e) { 81 e.printStackTrace(); 82 } 83 String sql = "DELETE FROM student WHERE id = 3;"; 84 try { 85 int count = stmt.executeUpdate(sql); 86 System.out.println(count); 87 } catch (SQLException e) { 88 e.printStackTrace(); 89 } 90 JdbcUtil.close(conn,stmt,rs); 91 } 92 }
4.3、执行DQL语句
1 package com.shore.b_statement; 2 3 import java.sql.Connection; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 import java.sql.Statement; 7 8 import org.junit.Test; 9 10 import com.bw.util.JdbcUtil; 11 12 /* 13 * 使用statement执行sql语句(查询操作语句) 14 * */ 15 public class Demo3 { 16 @Test 17 public void test1(){ 18 ResultSet rs = null; 19 Connection conn = null; 20 Statement stmt = null; 21 //获取连接 22 conn = JdbcUtil.getConnection(); 23 //创建statement 24 try { 25 stmt = conn.createStatement(); 26 } catch (SQLException e) { 27 e.printStackTrace(); 28 } 29 //准备sql语句 30 String sql = "SELECT * FROM student;";//查询表中所有数据 31 try { 32 rs=stmt.executeQuery(sql); 33 /*//移动光标 34 boolean flag=rs.next(); 35 if(flag){ 36 //取出值 37 //索引 38 int id=rs.getInt(1); 39 String name=rs.getString(2); 40 String sex=rs.getString(3); 41 System.out.println(id+","+name+","+sex); 42 }*/ 43 //遍历结果 44 while(rs.next()){ 45 int id=rs.getInt("id"); 46 String name=rs.getString("name"); 47 String sex=rs.getString("sex"); 48 System.out.println(id+","+name+","+sex); 49 } 50 } catch (SQLException e) { 51 e.printStackTrace(); 52 }finally{ 53 JdbcUtil.close(conn, stmt, rs); 54 } 55 } 56 }
5、使用PreparedStatement执行sql语句
1 package com.shore.c_prepared; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 8 import org.junit.Test; 9 10 import com.bw.util.JdbcUtil; 11 12 /* 13 * preparedStatement执行sql语句(有效防止sql注入的问题) 14 * */ 15 public class Demo1 { 16 //增加 17 @Test 18 public void testInsert(){ 19 Connection conn = null; 20 PreparedStatement stmt = null; 21 ResultSet rs = null; 22 //1.获取连接 23 conn = JdbcUtil.getConnection(); 24 //2准备预编译的sql 25 String sql = "INSERT INTO student(NAME,sex) VALUES(?,?);";//?表示一个参数的占位符 26 try { 27 //3执行预编译的sql语句(检查语法) 28 stmt = conn.prepareStatement(sql); 29 //4.设置参数 30 stmt.setString(1,"赵六"); //可用name作为参数代表“赵六” 从页面传值来此 31 stmt.setString(2,"女"); 32 //5.发送参数,执行sql 33 int count = stmt.executeUpdate(); 34 System.out.println("影响了"+count+"行"); 35 } catch (SQLException e) { 36 e.printStackTrace(); 37 }finally{ 38 JdbcUtil.close(conn, stmt, rs); 39 } 40 } 41 }
6、使用callablestaement执行sql语句,调用存储过程
MySQL存储过程 相关知识点:https://www.cnblogs.com/dshore123/p/10559182.html
1 -- 1.带有输入参数的存储过程 2 DELIMITER $ 3 CREATE PROCEDURE pro_test(IN sid INT) 4 BEGIN 5 SELECT * FROM student WHERE id=sid; 6 END $ 7 8 CALL pro_test(2);
1 -- 2.执行带有输出参数的存储过程 2 DELIMITER $ 3 CREATE PROCEDURE pro_test(IN sid INT,OUT sname VARCHAR(32)) 4 BEGIN 5 SELECT NAME INTO sname FROM student WHERE id=sid; 6 END $ 7 8 CALL pro_test(2,@sname); 9 SELECT @sname;
正文代码
1 package com.shore.d_callable; 2 3 import java.sql.CallableStatement; 4 import java.sql.Connection; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 8 import org.junit.Test; 9 10 import com.bw.util.JdbcUtil; 11 12 /** 13 * 使用CallableSatement调用存储过程 14 * @author lx 15 * 16 */ 17 public class Demo1 { 18 19 /* 20 * 1.带有输入参数的存储过程 21 * CALL pro_test(2) 22 * */ 23 @Test 24 public void test1(){ 25 Connection conn = null; 26 ResultSet rs = null; 27 CallableStatement stmt = null; 28 //获取连接 29 conn = JdbcUtil.getConnection(); 30 //准备sql 31 String sql = "CALL pro_test(?);"; //可以执行预编译的sql 32 try { 33 //预编译 34 stmt = conn.prepareCall(sql); 35 //设置参数 36 stmt.setInt(1, 2); 37 //注意:所有的存储过程的sql语句都是使用executeQuery 38 rs = stmt.executeQuery(); 39 //遍历起结果 40 while(rs.next()){ 41 int id = rs.getInt("id"); 42 String name = rs.getString("name"); 43 String sex = rs.getString("sex"); 44 System.out.println(id+","+name+","+sex); 45 } 46 } catch (SQLException e) { 47 e.printStackTrace(); 48 }finally{ 49 JdbcUtil.close(conn, stmt, rs); 50 } 51 } 52 /* 53 * 54 * 2.执行带有输出参数的存储过程 55 * */ 56 @Test 57 public void test2(){ 58 Connection conn = null; 59 ResultSet rs = null; 60 CallableStatement stmt = null; 61 //获取连接 62 conn = JdbcUtil.getConnection(); 63 //准备sql 64 String sql = "CALL pro_test(?,?);"; //第一个?是输入参数,第二个?是输出参数 65 try { 66 //预编译 67 stmt = conn.prepareCall(sql); 68 //设置参数 69 stmt.setInt(1, 2); 70 //设置输出参数 71 /* 72 *参数 一:参数的位置 73 *参数二:存储过程中输出参数的jdbc类型 varchar(32) 74 * */ 75 stmt.registerOutParameter(2,java.sql.Types.VARCHAR); 76 //发送参数,执行 77 stmt.executeQuery(); 78 /* //得到输出参数的值 79 * 索引值:预编译sql中的输出参数的位置 80 * */ 81 String result = stmt.getString(2);//getxxx方法专门用于获取存储过程中的输出参数 82 System.out.println(result); 83 } catch (SQLException e) { 84 e.printStackTrace(); 85 }finally{ 86 JdbcUtil.close(conn, stmt, rs); 87 } 88 } 89 }
附录
创建表:contact
1 create contact( 2 id varchar(32) primary key, 3 name varchar(32), 4 sxe varchar(32), 5 age int, 6 phone varchar(32), 7 email varchar(32), 8 qq varchar(32) 9 );
使用“增删改查(CRUD)”操作,连接数据库
1 package com.shore.dao.impl; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.util.ArrayList; 8 import java.util.List; 9 import java.util.UUID; 10 11 import com.shore.dao.ContactDAO; 12 import com.shore.entity.Contact; 13 import com.shore.util.JdbcUtil; 14 15 public class ContactDAOMySqlImpl implements ContactDAO{ 16 17 //添加数据 18 public void addContact(Contact contact) { 19 Connection conn; 20 PreparedStatement stmt = null; 21 ResultSet rs = null; 22 conn = JdbcUtil.getConnection(); 23 String sql = "insert into contact(id,name,sex,age,phone,email,qq) values(?,?,?,?,?,?,?)"; 24 try { 25 //执行预编译的sql语句(检查语法) 26 stmt = conn.prepareStatement(sql); 27 String id = UUID.randomUUID().toString().replace("-",""); 28 stmt.setString(1, id); 29 stmt.setString(2, contact.getName()); 30 stmt.setString(3, contact.getSex()); 31 stmt.setInt(4, contact.getAge()); 32 stmt.setString(5, contact.getPhone()); 33 stmt.setString(6, contact.getEmail()); 34 stmt.setString(7, contact.getQq()); 35 stmt.executeUpdate(); 36 } catch (SQLException e) { 37 e.printStackTrace(); 38 }finally{ 39 JdbcUtil.close(conn, stmt, rs); 40 } 41 } 42 43 //查询所有数据 44 public List<Contact> finAll() { 45 Connection conn; 46 PreparedStatement stmt = null; 47 ResultSet rs = null; 48 //获取连接 49 conn = JdbcUtil.getConnection(); 50 String sql = "select * from contact"; 51 try { 52 //执行预编译的sql语句(检查语法) 53 stmt = conn.prepareStatement(sql); 54 //执行sql; 55 rs = stmt.executeQuery(); 56 List<Contact> list = new ArrayList<Contact>(); 57 while(rs.next()){ 58 //创建Contact对象 59 Contact c = new Contact(); 60 c.setId(rs.getString("id")); 61 c.setName(rs.getString("name")); 62 c.setSex(rs.getString("sex")); 63 c.setAge(rs.getInt("age")); 64 c.setPhone(rs.getString("phone")); 65 c.setEmail(rs.getString("email")); 66 c.setQq(rs.getString("qq")); 67 list.add(c); 68 } 69 return list; 70 } catch (SQLException e) { 71 e.printStackTrace(); 72 throw new RuntimeException(); 73 }finally{ 74 JdbcUtil.close(conn, stmt, rs); 75 } 76 } 77 78 //根据id删除数据 79 public void delContact(String id) { 80 Connection conn; 81 PreparedStatement stmt = null; 82 ResultSet rs = null; 83 conn = JdbcUtil.getConnection(); 84 String sql = "delete from contact where id=?"; 85 try { 86 //执行预编译的sql语句(检查语法) 87 stmt = conn.prepareStatement(sql); 88 stmt.setString(1,id) 89 //发送参数,执行sql; 90 stmt.executeUpdate(); 91 } catch (SQLException e) { 92 e.printStackTrace(); 93 }finally{//关闭资源 94 JdbcUtil.close(conn, stmt, rs); 95 } 96 } 97 98 //修改数据 99 public void updateContact(Contact contact) { 100 Connection conn; 101 PreparedStatement stmt = null; 102 ResultSet rs = null; 103 conn = JdbcUtil.getConnection(); 104 String sql = "update contact set name=?,sex=?,age=?,phone=?,email=?,qq=? where id=?"; 105 try { 106 //执行预编译的sql语句(检查语法) 107 stmt=conn.prepareStatement(sql); 108 stmt.setString(1, contact.getName()); 109 stmt.setString(2, contact.getSex()); 110 stmt.setInt(3, contact.getAge()); 111 stmt.setString(4, contact.getPhone()); 112 stmt.setString(5, contact.getEmail()); 113 stmt.setString(6, contact.getQq()); 114 stmt.setString(7, contact.getId()); 115 stmt.executeUpdate(); 116 } catch (SQLException e) { 117 e.printStackTrace(); 118 }finally{ 119 JdbcUtil.close(conn, stmt, rs); 120 } 121 } 122 123 //根据id查询数据(作用于修改数据的时候) 124 public Contact findById(String id) { 125 Connection conn; 126 PreparedStatement stmt = null; 127 ResultSet rs = null; 128 //获取连接 129 conn = JdbcUtil.getConnection(); 130 String sql = "select * from contact where id=?"; 131 try { 132 //执行预编译的sql语句(检查语法) 133 stmt = conn.prepareStatement(sql); 134 stmt.setString(1, id); 135 rs = stmt.executeQuery(); 136 Contact c = null; 137 while(rs.next()){ 138 //创建Contact对象 139 c = new Contact(); 140 c.setId(rs.getString("id")); 141 c.setName(rs.getString("name")); 142 c.setSex(rs.getString("sex")); 143 c.setAge(rs.getInt("age")); 144 c.setPhone(rs.getString("phone")); 145 c.setEmail(rs.getString("email")); 146 c.setQq(rs.getString("qq")); 147 } 148 return c; 149 } catch (SQLException e) { 150 e.printStackTrace(); 151 throw new RuntimeException(); 152 }finally{ 153 JdbcUtil.close(conn, stmt, rs); 154 } 155 } 156 157 //判断账号昵称是否重复,若重复,页面端显示此账号已存在,请重新取名 158 public boolean checkContact(String name) { 159 Connection conn; 160 PreparedStatement stmt = null; 161 ResultSet rs = null; 162 //获取数据库的连接 163 conn = JdbcUtil.getConnection(); 164 //准备sql 165 String sql = "select * from contact where name = ?"; 166 try { 167 //执行预编译的sql语句(检查语法) 168 stmt = conn.prepareStatement(sql); 169 //设置参数 170 stmt.setString(1, name); 171 //发送参数,执行sql 172 rs = stmt.executeQuery(); 173 if(rs.next()){ 174 return true; 175 }else{ 176 return false; 177 } 178 } catch (SQLException e) { 179 e.printStackTrace(); 180 throw new RuntimeException(); 181 }finally{//关闭资源 182 JdbcUtil.close(conn, stmt, rs); 183 } 184 } 185 }
完整的JDBC封装过程,及调用jdbc的使用过程实例
db.properties 配置文件(配置了数据库的驱动、入口连接、用户名、密码),主要作用:方便以后修改
1 jdbcDriver=com.mysql.jdbc.Driver 2 url=jdbc:mysql://localhost:3306/school 3 userName=root 4 passWord=123456
JdbcUtils类,把不变动的、且每次都使用到的那部分代码封装起来
1 package com.shore.utils; 2 3 import java.io.InputStream; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 import java.util.Properties; 10 11 /** 12 * @author DSHORE/2019-5-29 13 * 14 */ 15 public class JdbcUtils { 16 //静态代码块执行后,这几个参数,就有值了 17 private static String jdbcDriver = ""; 18 private static String url = ""; 19 private static String userName = ""; 20 private static String passWord = ""; 21 22 private JdbcUtils() { 23 } 24 25 static {//静态代码块 26 try { 27 //读取配置文件db.properties,用于获取数据库的入口连接url、用户名、密码,以及数据库的驱动 28 InputStream inputStream = JdbcUtils.class.getResourceAsStream("/db.properties"); 29 Properties properties = new Properties(); 30 properties.load(inputStream);//加载文件 31 inputStream.close(); 32 jdbcDriver = properties.getProperty("jdbcDriver"); 33 url = properties.getProperty("url"); 34 userName = properties.getProperty("userName"); 35 passWord = properties.getProperty("passWord"); 36 Class.forName(jdbcDriver); //注册驱动 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } 40 } 41 42 //获取连接 43 public static Connection getConnection() throws SQLException { 44 return DriverManager.getConnection(url, userName, passWord); 45 } 46 47 //关闭资源(比较严谨的写法) 48 public static void close(Connection connection, Statement statement,ResultSet resultSet) { 49 if (resultSet != null) { 50 try { 51 resultSet.close(); 52 } catch (SQLException e) { 53 e.printStackTrace(); 54 }finally{ 55 if (statement != null) { 56 try { 57 statement.close(); 58 } catch (SQLException e) { 59 e.printStackTrace(); 60 }finally{ 61 if (connection != null) { 62 try { 63 connection.close(); 64 } catch (SQLException e) { 65 e.printStackTrace(); 66 } 67 } 68 } 69 } 70 } 71 } 72 } 73 }
↑ 此处封装已完成。
下面用个简单的例子来演示怎么使用:
1 package com.shore.test; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 8 import org.junit.Test; 9 10 import com.shore.utils.JdbcUtils; 11 12 /** 13 * @author DSHORE/2019-5-29 14 * 15 */ 16 public class jdbcTest { 17 18 @Test 19 public void testInsert(){ 20 Connection connection = null; 21 PreparedStatement preparedStatement = null; 22 ResultSet resultSet = null; 23 try { 24 //1.获取连接 25 connection = JdbcUtils.getConnection(); 26 //2.准备预编译的sql 27 String sql = "insert into teacher(sname,sex) values(?,?);";//?表示一个参数的占位符 28 //3.执行预编译的sql语句(检查语法) 29 preparedStatement = connection.prepareStatement(sql); 30 //4.设置参数 31 preparedStatement.setString(1,"赵六"); //可用name作为参数代表“赵六” 从页面传值来此 32 preparedStatement.setString(2,"女"); 33 //5.发送参数,执行sql 34 int count = preparedStatement.executeUpdate(); 35 System.out.println("影响了"+count+"行"); 36 } catch (SQLException e) { 37 e.printStackTrace(); 38 }finally{ 39 JdbcUtils.close(connection, preparedStatement, resultSet); 40 } 41 } 42 }
运行后,结果图:
原创作者:DSHORE 作者主页:http://www.cnblogs.com/dshore123/ 原文出自:https://www.cnblogs.com/dshore123/p/10582283.html 欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!) |