当前位置:Gxlcms > 数据库问题 > JDBC学习小结

JDBC学习小结

时间:2021-07-01 10:21:17 帮助过:6人阅读

连接数据的步骤:

1.注册驱动 :Class.forName(“com.mysql.jdbc.Driver”) 推荐这种方式,不会对具体的驱动类产生依赖;DriverManager.registerDriver(com.mysql.jdbc.Driver)
 会造成DriverManager中产生两个一样的驱动,并会对具体的驱动类产生依赖;System.setProperty(“jdbc.drivers”, “driver1:driver2”) 虽然不会对具体的驱动类产生依赖;但注册不太方便,所以很少使用。
2.建立连接(Connection) :Connection conn = DriverManager.getConnection(url, user, password);url格式: JDBC:子协议:子名称//主机名:端口/数据库名?属性名=属性值&...;User,password可以用“属性名=属性值”方式告诉数据库;其他参数如:useUnicode=true&characterEncoding=GBK。
3.创建执行SQL的语句(Statement):
4.执行语句
5.处理执行结果(ResultSet)
6.释放资源

1、注册数据库驱动的方式:

1)加载 JDBC 驱动需调用 Class 类的静态方法 forName(),向其传递要加载的 JDBC 驱动的类名;

技术分享
 1 @Test
 2 public void testDriverManager() throws Exception{
 3     //1. 准备连接数据库的 4 个字符串. 
 4     //驱动的全类名.
 5     String driverClass = "com.mysql.jdbc.Driver";
 6     //JDBC URL
 7     String jdbcUrl = "jdbc:mysql://localhost:3306/test";
 8     //user
 9     String user = "root";
10     //password
11     String password = "123456";
12         
13     //2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
14     Class.forName(driverClass);
15         
16     //3. 通过 DriverManager 的 getConnection() 方法获取数据库连接. 
17     Connection connection = 
18             DriverManager.getConnection(jdbcUrl, user, password);
19     System.out.println(connection); 
20         
21 }
View Code

2)Driver 是一个接口: 数据库厂商必须提供实现的接口. 能从其中获取数据库连接.可以通过 Driver 的实现类对象获取数据库连接.

技术分享
 1 @Test
 2 public void testDriver() throws SQLException {
 3     //1. 创建一个 Driver 实现类的对象
 4     Driver driver = new com.mysql.jdbc.Driver();
 5 
 6     //2. 准备连接数据库的基本信息: url, user, password
 7     String url = "jdbc:mysql://localhost:3306/test";
 8     Properties info = new Properties();
 9     info.put("user", "root");
10     info.put("password", "123456");
11         
12     //3. 调用 Driver 接口的 connect(url, info) 获取数据库连接
13     Connection connection = driver.connect(url, info);
14     System.out.println(connection);
15 }
View Code

2、获取数据库连接的方式:
1)DriverManager 是驱动的管理类:1). 可以通过重载的 getConnection() 方法获取数据库连接. 较为方便,2). 可以同时管理多个驱动程序: 若注册了多个数据库连接, 则调用 getConnection(),3)方法时传入的参数不同, 即返回不同的数据库连接。

例:Connection connection = DriverManager.getConnection(jdbcUrl, user, password);

2)Driver 是一个接口: 数据库厂商必须提供实现的接口. 能从其中获取数据库连接.可以通过 Driver 的实现类对象获取数据库连接.

例:Connection connection = driver.connect(url, info);

3.创建执行SQL的语句(statement、preparedstatement):

通过 JDBC 向指定的数据表中插入一条记录. 
  a. Statement: 用于执行 SQL 语句的对象
  1). 通过 Connection 的 createStatement() 方法来获取
  2). 通过 executeUpdate(sql) 可以执行 SQL 语句.
  3). 传入的 SQL 可以是 INSRET, UPDATE 或 DELETE. 但不能是 SELECT
 
  b. Connection、Statement 都是应用程序和数据库服务器的连接资源. 使用后一定要关闭.
   需要在 finally 中关闭 Connection 和 Statement 对象. 
   
  c. 关闭的顺序是: 先关闭后获取的. 即先关闭 Statement 后关闭 Connection

示例代码如下:

技术分享
 1 @Test
 2 public void testStatement() throws Exception{
 3     //1. 获取数据库连接
 4     Connection conn = null;
 5     Statement statement = null;
 6         
 7     try {
 8         conn = JDBCTools.getConnection();
 9         
10         //3. 准备插入的 SQL 语句
11         String sql = null;
12         
13                //sql = "INSERT INTO customers (NAME, EMAIL, BIRTH) " +
14                    //"VALUES(‘XYZ‘, ‘xyz@atguigu.com‘, ‘1990-12-12‘)";
15               //sql = "DELETE FROM customers WHERE id = 1";
16         sql = "UPDATE customers SET name = ‘TOM‘ " +
17                 "WHERE id = 4";
18         System.out.println(sql);
19             
20           //4. 执行插入. 
21           //1). 获取操作 SQL 语句的 Statement 对象: 
22          //调用 Connection 的 createStatement() 方法来获取
23           statement = conn.createStatement();
24             
25          //2). 调用 Statement 对象的 executeUpdate(sql) 执行 SQL 语句进行插入
26           statement.executeUpdate(sql);
27     } catch (Exception e) {
28         e.printStackTrace();
29     } finally{
30         JDBCTools.release(statement,conn);
31     }     
View Code

4.处理执行结果(ResultSet):
ResultSet: 结果集. 封装了使用 JDBC 进行查询的结果. 
   a. 调用 Statement 对象的 executeQuery(sql) 可以得到结果集.
   b. ResultSet 返回的实际上就是一张数据表. 有一个指针指向数据表的第一样的前面.可以调用 next() 方法检测下一行是否有效. 若有效该方法返回 true, 且指针下移. 相当于Iterator 对象的 hasNext() 和 next() 方法的结合体
   c. 当指针对位到一行时, 可以通过调用 getXxx(index) 或 getXxx(columnName),获取每一列的值. 例如: getInt(1), getString("name")
   d. ResultSet 当然也需要进行关闭.

示例代码如下:

技术分享
 1 @Test
 2 public void testResultSet(){
 3     //获取 id=4 的 customers 数据表的记录, 并打印
 4         
 5     Connection conn = null;
 6     Statement statement = null;
 7     ResultSet rs = null;
 8         
 9     try {
10         //1. 获取 Connection
11         conn = JDBCTools.getConnection();
12         System.out.println(conn);
13             
14         //2. 获取 Statement
15         statement = conn.createStatement();
16         System.out.println(statement);
17             
18         //3. 准备 SQL
19         String sql = "SELECT id, name, email, birth " +
20                     "FROM customers";
21             
22         //4. 执行查询, 得到 ResultSet
23         rs = statement.executeQuery(sql);
24         System.out.println(rs);
25             
26         //5. 处理 ResultSet
27         while(rs.next()){
28             int id = rs.getInt(1);
29             String name = rs.getString("name");
30             String email = rs.getString(3);
31             Date birth = rs.getDate(4);
32                 
33             System.out.println(id);
34             System.out.println(name);
35             System.out.println(email);
36             System.out.println(birth);
37         }
38             
39     } catch (Exception e) {
40         e.printStackTrace();
41     } finally{
42         //6. 关闭数据库资源. 
43         JDBCTools.release(rs, statement, conn);
44     }
45         
46 }
View Code

JDBC工具模板(JDBCTools)配置如下:

技术分享
 1 import java.io.InputStream;
 2 import java.sql.Connection;
 3 import java.sql.DriverManager;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.sql.Statement;
 7 import java.util.Properties;
 8 
 9 /**
10  * 操作 JDBC 的工具类. 其中封装了一些工具方法 Version 1
11  */
12 public class JDBCTools {
13 
14     public static void release(ResultSet rs, 
15             Statement statement, Connection conn) {
16         if(rs != null){
17             try {
18                 rs.close();
19             } catch (SQLException e) {
20                 e.printStackTrace();
21             }
22         }
23         
24         
25         if (statement != null) {
26             try {
27                 statement.close();
28             } catch (Exception e2) {
29                 e2.printStackTrace();
30             }
31         }
32 
33         if (conn != null) {
34             try {
35                 conn.close();
36             } catch (Exception e2) {
37                 e2.printStackTrace();
38             }
39         }
40     }
41     
42     /**
43      * 关闭 Statement 和 Connection
44      * @param statement
45      * @param conn
46      */
47     public static void release(Statement statement, Connection conn) {
48         if (statement != null) {
49             try {
50                 statement.close();
51             } catch (Exception e2) {
52                 e2.printStackTrace();
53             }
54         }
55 
56         if (conn != null) {
57             try {
58                 conn.close();
59             } catch (Exception e2) {
60                 e2.printStackTrace();
61             }
62         }
63     }
64 
65     /**
66      * 1. 获取连接的方法. 通过读取配置文件从数据库服务器获取一个连接.
67      * 
68      * @return
69      * @throws Exception
70      */
71     public static Connection getConnection() throws Exception {
72         // 1. 准备连接数据库的 4 个字符串.
73         // 1). 创建 Properties 对象
74         Properties properties = new Properties();
75 
76         // 2). 获取 jdbc.properties 对应的输入流
77         InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream(
78                 "jdbc.properties");
79 
80         // 3). 加载 2) 对应的输入流
81         properties.load(in);
82 
83         // 4). 具体决定 user, password 等4 个字符串.
84         String user = properties.getProperty("user");
85         String password = properties.getProperty("password");
86         String jdbcUrl = properties.getProperty("jdbcUrl");
87         String driver = properties.getProperty("driver");
88 
89         // 2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
90         Class.forName(driver);
91 
92         // 3. 通过 DriverManager 的 getConnection() 方法获取数据库连接.
93         return DriverManager.getConnection(jdbcUrl, user, password);
94     }
95 
96 }
View Code

 

技术分享
1 driver=com.mysql.jdbc.Driver
2 jdbcUrl=jdbc:mysql://localhost:3306/test
3 user=root
4 password=123456
View Code

 

二、实现数据库增删改查

1.创立数据库表 examstudent;

技术分享
 1 /*
 2 Navicat MySQL Data Transfer
 3 
 4 Source Server         : localhost
 5 Source Server Version : 50524
 6 Source Host           : localhost:3306
 7 Source Database       : examstudent
 8 
 9 Target Server Type    : MYSQL
10 Target Server Version : 50524
11 File Encoding         : 65001
12 
13 Date: 2015-06-27 15:49:22
14 */
15 
16 SET FOREIGN_KEY_CHECKS=0;
17 
18 -- ----------------------------
19 -- Table structure for examstudent
20 -- ----------------------------
21 DROP TABLE IF EXISTS `examstudent`;
22 CREATE TABLE `examstudent` (
23   `flowid` int(11) NOT NULL,
24   `type` int(11) DEFAULT NULL,
25   `idcard` varchar(18) DEFAULT NULL,
26   `examcard` varchar(15) DEFAULT NULL,
27   `studentname` varchar(20) DEFAULT NULL,
28   `location` varchar(20) DEFAULT NULL,
29   `grade` int(11) DEFAULT NULL,
30   PRIMARY KEY (`flowid`)
31 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
View Code

2.向数据库中添加如下数据

技术分享

3. 在 eclipse 中建立 java 程序:输入身份证号或准考证号可以查询到学生的基本信息。

4.完成学生信息的删除功能

示例代码如下:

 jdbc.properties

技术分享
1 user=root
2 password=123456
3 driverClass=com.mysql.jdbc.Driver
4 url=jdbc:mysql://localhost:3306/examstudent
View Code

student.java

技术分享
  1 package com.atguigu.jdbc;
  2 
  3 public class Student {
  4 
  5     // 流水号
  6     private int flowId;
  7     // 考试的类型
  8     private int type;
  9     // 身份证号
 10     private String idCard;
 11     // 准考证号
 12     private String examCard;
 13     // 学生名
 14     private String studentName;
 15     // 学生地址
 16     private String location;
 17     // 考试分数.
 18     private int grade;
 19 
 20     public int getFlowId() {
 21         return flowId;
 22     }
 23 
 24     public void setFlowId(int flowId) {
 25         this.flowId = flowId;
 26     }
 27 
 28     public int getType() {
 29         return type;
 30     }
 31 
 32     public void setType(int type) {
 33         this.type = type;
 34     }
 35 
 36     public String getIdCard() {
 37         return idCard;
 38     }
 39 
 40     public void setIdCard(String idCard) {
 41         this.idCard = idCard;
 42     }
 43 
 44     public String getExamCard() {
 45         return examCard;
 46     }
 47 
 48     public void setExamCard(String examCard) {
 49         this.examCard = examCard;
 50     }
 51 
 52     public String getStudentName() {
 53         return studentName;
 54     }
 55 
 56     public void setStudentName(String studentName) {
 57         this.studentName = studentName;
 58     }
 59 
 60     public String getLocation() {
 61         return location;
 62     }
 63 
 64     public void setLocation(String location) {
 65         this.location = location;
 66     }
 67 
 68     public int getGrade() {
 69         return grade;
 70     }
 71 
 72     public void setGrade(int grade) {
 73         this.grade = grade;
 74     }
 75 
 76     public Student(int flowId, int type, String idCard, String examCard,
 77             String studentName, String location, int grade) {
 78         super();
 79         this.flowId = flowId;
 80         this.type = type;
 81         this.idCard = idCard;
 82         this.examCard = examCard;
 83         this.studentName = studentName;
 84         this.location = location;
 85         this.grade = grade;
 86     }
 87 
 88     public Student() {
 89         // TODO Auto-generated constructor stub
 90     }
 91 
 92     @Override
 93     public String toString() {
 94         return "Student [flowId=" + flowId + ", type=" + type + ", idCard="
 95                 + idCard + ", examCard=" + examCard + ", studentName="
 96                 + studentName + ", location=" + location + ", grade=" + grade
 97                 + "]";
 98     }
 99 
100 }
View Code

JDBCTools.java

技术分享
  1 package cky.test;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.sql.Connection;
  6 import java.sql.DriverManager;
  7 import java.sql.PreparedStatement;
  8 import java.sql.ResultSet;
  9 import java.sql.SQLException;
 10 import java.sql.Statement;
 11 import java.util.Properties;
 12 
 13 public class JDBCTools {
 14 
 15     /**
 16      * 执行 SQL 语句, 使用 PreparedStatement
 17      * @param sql
 18      * @param args: 填写 SQL 占位符的可变参数
 19      */
 20     public static void update(String sql, Object ... args){
 21         Connection connection = null;
 22         PreparedStatement preparedStatement = null;
 23         
 24         try {
 25             connection = JDBCTools.getConnection();
 26             preparedStatement = connection.prepareStatement(sql);
 27             
 28             for(int i = 0; i < args.length; i++){
 29                 preparedStatement.setObject(i + 1, args[i]);
 30             }
 31             
 32             preparedStatement.executeUpdate();
 33             
 34         } catch (Exception e) {
 35             e.printStackTrace();
 36         } finally{
 37             JDBCTools.releaseDB(null, preparedStatement, connection);
 38         }
 39     }
 40     
 41     /**
 42      * 执行 SQL 的方法
 43      * 
 44      * @param sql: insert, update 或 delete。 而不包含 select
 45      */
 46     public static void update(String sql) {
 47         Connection connection = null;
 48         Statement statement = null;
 49 
 50         try {
 51             // 1. 获取数据库连接
 52             connection = getConnection();
 53 
 54             // 2. 调用 Connection 对象的 createStatement() 方法获取 Statement 对象
 55             statement = connection.createStatement();
 56 
 57             // 4. 发送 SQL 语句: 调用 Statement 对象的 executeUpdate(sql) 方法
 58             statement.executeUpdate(sql);
 59 
 60         } catch (Exception e) {
 61             e.printStackTrace();
 62         } finally {
 63             // 5. 关闭数据库资源: 由里向外关闭.
 64             releaseDB(null, statement, connection);
 65         }
 66     }
 67 
 68     /**
 69      * 释放数据库资源的方法
 70      * 
 71      * @param resultSet
 72      * @param statement
 73      * @param connection
 74      */
 75     public static void releaseDB(ResultSet resultSet, Statement statement,
 76             Connection connection) {
 77 
 78         if (resultSet != null) {
 79             try {
 80                 resultSet.close();
 81             } catch (SQLException e) {
 82                 e.printStackTrace();
 83             }
 84         }
 85 
 86         if (statement != null) {
 87             try {
 88                 statement.close();
 89             } catch (SQLException e) {
 90                 e.printStackTrace();
 91             }
 92         }
 93 
 94         if (connection != null) {
 95             try {
 96                 connection.close();
 97             } catch (SQLException e) {
 98                 e.printStackTrace();
 99             }
100         }
101 
102     }
103 
104     /**
105      * 获取数据库连接的方法
106      */
107     public static Connection getConnection() throws IOException,
108             ClassNotFoundException, SQLException {
109         // 0. 读取 jdbc.properties
110         /**
111          * 1). 属性文件对应 Java 中的 Properties 类 2). 可以使用类加载器加载 bin 目录(类路径下)的文件
112          */
113         Properties properties = new P                    

人气教程排行