222

                    Java基础-面向接口编程-JDBC详解

                                      作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

  

一.JDBC概念和数据库驱动程序

  JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。是Java访问数据库的标准规范。本篇博客使用的介绍的是Java链接MySQL数据库,如果对MySQL数据不是很了解的小伙伴请参考:http://www.cnblogs.com/yinzhengjie/p/9011342.html

  JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。JDBC需要连接驱动,驱动是两个设备要进行通信,满足一定通信数据格式,数据格式由设备提供商规定,设备提供商为设备提供驱动软件,通过软件可以与该设备进行通信。

  本篇博客使用的是mysql的驱动mysql-connector-java-5.1.39-bin.jar,若没有安装包请自行下载,若在网上没有找到相应的解决方案,别担心,我已经帮你把坑踩好了,请参考:http://www.cnblogs.com/yinzhengjie/p/9017416.html

二.JDBC原理

  Java提供访问数据库规范称为JDBC,而生产厂商提供规范的实现类称为驱动。JDBC是接口,驱动是接口的实现,没有驱动将无法完成数据库连接,从而不能操作数据库!每个数据库厂商都需要提供自己的驱动,用来连接自己公司的数据库,也就是说驱动一般都由数据库生成厂商提供。

三.JDBC的开发步骤

 1>.JDBC操作数据库的步骤

  a>.注册驱动

    告知JVM使用的是哪一个数据库的驱动。

  b>.获得链接

    使用JDBC中的类,完成对MySQL数据库的链接。

  c>.获得语句执行平台

    通过链接对象获取对SQL语句的执行者对象。

  d>.执行SQL语句

    使用执行者对象,向数据库执行SQL语句,获取到数据库执行后的结果。

  e>.处理结果

    就是我们当我们拿到数据库执行后的结果想要完成的业务逻辑。

  f>.释放资源

    关闭网络链接,跟IO流类似,调用其close方法即可。

2>.导入MySQL数据库驱动程序jar包

  a>.在当前项目下,创建lib目录,在lib目录下创建MySQL目录(用于标识该目录只存放MySQL相关驱动),并将下载的好的按照保导入该文件夹中。

  b>.将下载后的Java包添加到项目中的环境变量中

  c>.导入MySQL驱动成功标志

3>.准备数据库数据(我开发环境在虚拟机上安装的,真正的MySQL服务安装在宿主机上,模拟的是生产环境中链接服务器)

 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A/
 4 EMAIL:[email protected]
 5 */
 6 
 7 
 8 #创建表结构
 9 create table Classmate(
10     ID int(11) NOT NULL primary key AUTO_INCREMENT,
11     Name varchar(30) COLLATE gbk_bin DEFAULT NULL,
12     Age int DEFAULT NULL,
13     Job varchar(50),
14     Chinese int,
15     English int,
16     Math int,
17     Physics int,
18     Chemistry int,
19     Biology int
20 );
21 
22 #往表里添加数据
23 insert into Classmate values(null,'王建军',30,'Java讲师',100,98,99,96,97,100);
24 insert into Classmate values(null,'常庆林',28,'Linux讲师',100,100,98,93,99,96);
25 insert into Classmate values(null,'徐培成',35,'BigData讲师',100,100,100,98,96,100);
26 insert into Classmate values(null,'李永强',30,'javaEE开发工程师',100,93,91,74,89,100);
27 insert into Classmate values(null,'赵子昂',24,'python开发工程师',98,93,91,74,89,100);
28 insert into Classmate values(null,'桂阳',25,'C++开发工程师',100,98,93,91,99,82);
29 insert into Classmate values(null,'肖云龙',24,'Golang开发工程师',93,97,85,100,93,69);
30 insert into Classmate values(null,'李洋',23,'C#开发工程师',100,98,99,96,97,100);
31 insert into Classmate values(null,'卜孟龙',30,'BigData开发',98,93,100,100,73,92);
32 insert into Classmate values(null,'罗大鹏',22,'Java开发工程师',100,84,91,87,100,93);
33 insert into Classmate values(null,'尹正杰',26,'高级运维工程师',100,100,100,100,100,100);

四.JDBC执行insert语句( Statement接口的实现类对象)

 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:[email protected]
 5 */
 6 package cn.org.yinzhengjie.note;
 7 
 8 import java.sql.Connection;
 9 import java.sql.DriverManager;
10 import java.sql.ResultSet;
11 import java.sql.Statement;
12 
13 public class JDBCDemo {
14 
15     public static void main(String[] args) throws Exception {
16         
17         //1.注册驱动,利用java反射技术,将驱动类加入到内容
18         /*使用java.sql.DriverManager类静态方法 registerDriver(Driver driver)
19           Diver是一个接口,参数传递,MySQL驱动程序中的实现类
20           DriverManager.registerDriver(new Driver());
21            驱动类源代码,注册2次驱动程序 */
22         Class.forName("com.mysql.jdbc.Driver");
23         //2.获得数据库连接  DriverManager类中静态方法
24         /*static Connection getConnection(String url, String user, String password)  
25             返回值是Connection接口的实现类,在mysql驱动程序
26             url: 数据库地址  jdbc:mysql://连接主机IP:端口号//数据库名字  */
27         String url = "jdbc:mysql://192.168.0.254:5200/yinzhengjie";
28         String username="root";
29         String password="yinzhengjie";
30         Connection conn = DriverManager.getConnection(url, username, password);
31         //3.获得语句执行平台, 通过数据库连接对象,获取到SQL语句的执行者对象
32         /* conn对象调用方法   Statement createStatement() 获取Statement对象,将SQL语句发送到数据库返回值是 Statement接口的实现类对象.*/
33         Statement stat = conn.createStatement();
34         //    4.执行sql语句
35         /* 通过执行者对象调用方法执行SQL语句,获取结果 int executeUpdate(String sql)  执行数据库中的SQL语句, insert,delete,update操作,返回值int,操作成功数据表多少行 */
36         String sql = "insert into Classmate values(null,'邓西',27,'DBA开发工程师',98,100,81,70,100,90);";
37         int row = stat.executeUpdate(sql);
38         System.out.printf("表中有【%d】行发生了改变!",row);
39         //6.释放资源  一堆close()
40         stat.close();
41         conn.close();
42     }
43 }
44 
45 
46 /*
47 以上代码执行结果如下:
48 表中有【1】行发生了改变!
49 */

五.JDBC执行select语句(ResultSet接口的实现类)

 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:[email protected]
 5 */
 6 package cn.org.yinzhengjie.note;
 7 
 8 import java.sql.Connection;
 9 import java.sql.DriverManager;
10 import java.sql.ResultSet;
11 import java.sql.Statement;
12 /*
13  *  JDBC技术,查询数据表,获取结果集
14  */
15 public class JDBCDemo1 {
16     public static void main(String[] args) throws Exception{
17         //1. 注册驱动
18         Class.forName("com.mysql.jdbc.Driver");
19         //2. 获取连接对象
20         String url = "jdbc:mysql://192.168.0.254:5200/yinzhengjie";
21         String username="root";
22         String password="yinzhengjie";
23         Connection conn = DriverManager.getConnection(url, username, password);
24         //3 .获取执行SQL 语句对象
25         Statement stat = conn.createStatement();
26         // 拼写查询的SQL
27         String sql = "select * from classmate";
28         //4. 调用执行者对象方法,执行SQL语句获取结果集
29         /* ResultSet executeQuery(String sql)  执行SQL语句中的select查询,返回值ResultSet接口的实现类对象,实现类在mysql驱动中*/
30         ResultSet rs = stat.executeQuery(sql);
31         //5 .处理结果集
32         // ResultSet接口方法 boolean next() 返回true,有结果集,返回false没有结果集
33         //获取结果集中的数据,一种是逐行获取每列的内容,如果知道是字符串就用getString方法接住,类型为String,如果知道是数字则用getInt方式接着,类型为int,如果你不知道此列的类型可以用getObject接住,类型为Object。
34         /*根据每列的长度进行取值,不推荐使用
35         while(rs.next()){
36             int id = rs.getInt(1);
37             String name = rs.getString(2);
38             int age = rs.getInt(3);
39             String job = rs.getString(4);
40             int Chinese = rs.getInt(5);
41             int English = rs.getInt(6);
42             int Math = rs.getInt(7);
43             int Physics = rs.getInt(8);
44             int Chemistry = rs.getInt(9);
45             int Biology = rs.getInt(10);
46             System.out.println(id +","+ name +","+ age +","+ job +","+ Chinese+","+ English+","+ Math+","+ Physics+","+ Chemistry+","+ Biology);
47         }*/
48         //除了上面的取值方式,当然还可以用列明的方式取值啦。这样你可以清楚的知道自己取出来的是什么数据,推荐使用该方法。
49         while(rs.next()){
50             int id = rs.getInt("id");
51             String name = rs.getString("name");
52             int age = rs.getInt("age");
53             String job = rs.getString("job");
54             int Chinese = rs.getInt("Chinese");
55             int English = rs.getInt("English");
56             int Math = rs.getInt("Math");
57             int Physics = rs.getInt("Physics");
58             int Chemistry = rs.getInt("Chemistry");
59             int Biology = rs.getInt("Biology");
60             System.out.println(id +","+ name +","+ age +","+ job +","+ Chinese+","+ English+","+ Math+","+ Physics+","+ Chemistry+","+ Biology);
61         }
62         //6.释放资源  一堆close()
63         rs.close();
64         stat.close();
65         conn.close();
66     }
67 }
68 
69 
70 
71 /*
72 以上代码执行结果如下:
73 1,王建军,30,Java讲师,100,98,99,96,97,100
74 2,常庆林,28,Linux讲师,100,100,98,93,99,96
75 3,徐培成,35,BigData讲师,100,100,100,98,96,100
76 4,李永强,30,javaEE开发工程师,100,93,91,74,89,100
77 5,赵子昂,24,python开发工程师,98,93,91,74,89,100
78 6,桂阳,25,C++开发工程师,100,98,93,91,99,82
79 7,肖云龙,24,Golang开发工程师,93,97,85,100,93,69
80 8,李洋,23,C#开发工程师,100,98,99,96,97,100
81 9,卜孟龙,30,BigData开发,98,93,100,100,73,92
82 10,罗大鹏,22,Java开发工程师,100,84,91,87,100,93
83 11,尹正杰,26,高级运维工程师,100,100,100,100,100,100
84 12,邓西,27,DBA开发工程师,98,100,81,70,100,90
85 */

六.Java防SQL注入的解决方案

  1 /*
  2 @author :yinzhengjie
  3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
  4 EMAIL:[email protected]
  5 */
  6 package cn.org.yinzhengjie.note;
  7 
  8 import java.sql.Connection;
  9 import java.sql.DriverManager;
 10 import java.sql.PreparedStatement;
 11 import java.sql.Statement;
 12 
 13 /*
 14  * 
 15  * 1.statement使用的不方便
 16  * 2.sql注入的问题
 17  *     在SQL语句中使用了系统自带的关键字 or and ,让where条件判断失效
 18  * 
 19  * prepareStatement:
 20  *     1.sql语句不用在拼字符串
 21  *     2.防止sql注入问题
 22  * 
 23  */
 24 public class CURDDemo {
 25 
 26     public static void main(String[] args) throws Exception {
 27 //        insertTest();
 28         insertTest2();        //优化后的代码
 29 //         deleteTest();
 30 //         deleteTest2();        //优化后的代码
 31     }
 32 
 33     // 删除方法,存在SQL注入风险!
 34     private static void deleteTest() throws Exception {
 35         Class.forName("com.mysql.jdbc.Driver");
 36 
 37         Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.254:5200/yinzhengjie", "root", "yinzhengjie");
 38 
 39         Statement st = conn.createStatement();
 40 
 41         int id = 4;
 42         //定义我们想要执行的语句
 43 //        String sql = "delete from emp where eid = " + id ";
 44         //一些对SQL语句小朋友喜欢搞点事情,把上面的代码添头加醋,就生成了以下代码(" or 1 = 1"),最终会导致where匹配条件失效,导致清空掉了整个数据库内容!是不是有点小惊讶呢?
 45         String sql = "delete from classmate where id = " + id + " or 1 = 1";
 46         //除了上面说的SQL注入情况外,按照上面的拼接字符串真的让人欲哭无泪啊,庆幸的是我上面测试环境参数相对较少,要是在实际生产环境中就有50个参数要传递那只要你的小手一哆嗦就很容易出错呢!
 47         int i = st.executeUpdate(sql);
 48 
 49         if (i != 0) {
 50             System.out.println("删除成功");
 51         }
 52 
 53         st.close();
 54         conn.close();
 55     }
 56 
 57     // 删除优化,解决掉SQL注入风险以及拼接字符串的烦恼!
 58     private static void deleteTest2() throws Exception {
 59         Class.forName("com.mysql.jdbc.Driver");
 60         Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.254:5200/yinzhengjie", "root", "yinzhengjie");
 61         /*调用Connection接口的方法prepareStatement,获取PrepareStatement接口的实现类,方法中参数,SQL语句中的参数全部采用问号占位符*/
 62         String sql = "delete from classmate where id = ?";
 63         PreparedStatement pst = conn.prepareStatement(sql);
 64         //我们在传参数的时候
 65 //        pst.setInt(1, 12);
 66         //这个时候我们再去模仿SQL注入,发现数据库真实删除的只有第二条。关于后面的“or 1 = 1”压根就没有执行!!,是不是很高大上?
 67         pst.setString(1," 2 or 1 = 1" );
 68         int i = pst.executeUpdate();
 69 
 70         if (i != 0) {
 71             System.out.println("删除成功");
 72         }
 73 
 74         pst.close();
 75         conn.close();
 76     }
 77 
 78     // 增,也能存在SQL注入的风险,不推荐使用!
 79     private static void insertTest() throws Exception {
 80         // 注册驱动
 81         Class.forName("com.mysql.jdbc.Driver");
 82         // 获取连接
 83         Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.254:5200/yinzhengjie", "root", "yinzhengjie");
 84         // 创建statement对象
 85         Statement st = conn.createStatement();
 86         // 执行sql语句
 87         // 真实场景中,sql中的数据都是从外界获取的.
 88         
 89         String name = "方合意";
 90         int age = 21;
 91         String job = "Python开发工程师";
 92         int chinese = 100;
 93         int english = 89;
 94         int math = 98;
 95         int physics = 91;
 96         int chemistry = 73;
 97         int biology = 89;
 98         
 99         String sql = "insert into classmate values(null,'" + name + "', " + age + ", '" + job+ "', " + chinese+ ", " + english+ ", " + math + ", " + physics + ", " + chemistry +", " + biology+ ")";
100 
101         int i = st.executeUpdate(sql);
102         // 判断插入语句是否执行成功
103         if (i != 0) {
104             System.out.println("插入数据成功");
105         }
106         st.close();
107         conn.close();
108     }
109 
110     //增,防止SQL注入版本!
111     private static void insertTest2() throws Exception {
112         // 注册驱动
113         Class.forName("com.mysql.jdbc.Driver");
114 
115         // 获取连接
116         Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.254:5200/yinzhengjie", "root", "yinzhengjie");
117         /*调用Connection接口的方法prepareStatement,获取PrepareStatement接口的实现类,方法中参数,SQL语句中的参数全部采用问号占位符*/
118         String sql = "insert into classmate values (null,?,?,?,?,?,?,?,?,?)";
119 
120         PreparedStatement pst = conn.prepareStatement(sql);
121         //调用pst对象set方法,设置问号占位符上的参数
122         pst.setString(1, "邓聪");
123         pst.setInt(2, 28);
124         pst.setString(3, "网络工程师");
125         pst.setInt(4, 100);
126         pst.setInt(5, 98);
127         pst.setInt(6, 89);
128         pst.setInt(7, 86);
129         pst.setInt(8, 97);
130         pst.setInt(9, 94);
131 
132         int i = pst.executeUpdate();
133         // 判断插入语句是否执行成功
134         if (i != 0) {
135             System.out.println("插入数据成功");
136         }
137 
138         pst.close();
139         conn.close();
140 
141     }
142 }
143 
144 
145 /*
146 以上代码执行结果如下:
147 插入数据成功
148 */

八.JDBC的工具类和测试

1 DriverName=com.mysql.jdbc.Driver
2 #zai "url" lu jing hou jia "?useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true" ke yi kai qi pi chu li mo shi !
3 url=jdbc:mysql://192.168.0.254:5200/yinzhengjie?useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true
4 user=root
5 password=yinzhengjie
config.properties 文件内容
 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:[email protected]
 5 */
 6 package cn.org.yinzhengjie.note1;
 7 
 8 import java.io.FileInputStream;
 9 import java.io.IOException;
10 import java.sql.Connection;
11 import java.sql.DriverManager;
12 import java.util.Properties;
13 
14 /*
15  * 获取数据库连接的工具类
16  * 在获取连接对象的方法中,首先是注册驱动,实际上没有必要
17  * 注册驱动只需要执行一次就OK
18  * 
19  */
20 public class Utils {
21     
22     private Utils(){}
23     
24     private static Properties p = new Properties();
25     private static String driver;
26     private static String url;
27     private static String user;
28     private static String password;
29     
30     //加载配置文件
31     static{
32         try {
33 //            p.load(Utils.class.getClassLoader().getResourceAsStream("config.properties"));
34             p.load(new FileInputStream("config.properties"));
35             driver = p.getProperty("DriverName");
36             url = p.getProperty("url");
37             user = p.getProperty("user");
38             password = p.getProperty("password");
39         } catch (IOException e) {
40             e.printStackTrace();
41         }
42     }
43     
44     //注册驱动
45     static{
46         //注册驱动
47         try {
48             Class.forName(driver);
49         } catch (ClassNotFoundException e) {
50             e.printStackTrace();
51         }
52     }
53     
54     public static Connection getConnect() throws Exception{
55         //获取连接
56         Connection conn = DriverManager.getConnection(url, user, password);
57         return conn;
58     }
59 
60 }
Utils.java 文件内容
  1 /*
  2 @author :yinzhengjie
  3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
  4 EMAIL:[email protected]
  5 */
  6 package cn.org.yinzhengjie.note1;
  7 
  8 import java.sql.Connection;
  9 import java.sql.ResultSet;
 10 import java.sql.Statement;
 11 import org.junit.Test;
 12 
 13 
 14 public class Demo {
 15     @Test        //注意,这个Test是单元测试,程序员不需要写main方法就可以测试!选中方法名运行即可。
 16     public void insertTest() throws Exception{
 17         //使用工具类获取连接
 18         Connection conn = Utils.getConnect();
 19         
 20         // 创建statement对象
 21         Statement st = conn.createStatement();
 22 
 23         // 执行sql语句
 24         String sql = "insert into Classmate values(null,'陶涛',22,'网络工程师',100,100,72,93,79,81)";
 25         int i = st.executeUpdate(sql);
 26         // 判断插入语句是否执行成功
 27         if (i != 0) {
 28             System.out.println("插入数据成功");
 29         }
 30 
 31         st.close();
 32         conn.close();
 33     }
 34     
 35     @Test        //注意,这个Test是单元测试,程序员不需要写main方法就可以测试!选中方法名运行即可。
 36     public void deleteTest() throws Exception{
 37         Connection conn = Utils.getConnect();
 38         
 39         Statement st = conn.createStatement();
 40         String name = "陶涛";
 41         //注意,字段需要用单引号引起来,这是数据库的语法规则!因此我们需要在字符串两侧加上相应的单引号!
 42         String sql = "delete from classmate where name = '" + name + "'";    
 43 
 44         int i = st.executeUpdate(sql);
 45 
 46         if (i != 0) {
 47             System.out.println("删除成功");
 48         }
 49 
 50         st.close();
 51         conn.close();
 52     }
 53     
 54     @Test        //注意,这个Test是单元测试,程序员不需要写main方法就可以测试!选中方法名运行即可。
 55     public void updateTest() throws Exception{
 56         
 57         Connection conn = Utils.getConnect();
 58         
 59         Statement st = conn.createStatement();
 60         
 61         String sql = "update classmate set English = English + 120";
 62         int i = st.executeUpdate(sql);
 63         
 64         if (i != 0) {
 65             System.out.println("修改成功");
 66         }
 67 
 68         st.close();
 69         conn.close();
 70     }
 71     
 72     @Test        //注意,这个Test是单元测试,程序员不需要写main方法就可以测试!选中方法名运行即可。
 73     public void selectTest() throws Exception{
 74         Connection conn = Utils.getConnect();
 75         Statement st = conn.createStatement();
 76         
 77     String sql = "select * from classmate where id = 11";
 78         
 79         //执行查询语句!
 80         ResultSet rs = st.executeQuery(sql);
 81         
 82         while(rs.next()){
 83             //如果你不知道返回值是什么类型的话,可以用getObject来接住哟!!!
 84             Object id = rs.getObject("id");
 85             Object name = rs.getObject("name");
 86             Object age = rs.getObject("age");
 87             Object job = rs.getObject("job");
 88             Object chinese = rs.getObject("chinese");
 89             Object english = rs.getObject("english");
 90             Object math = rs.getObject("math");
 91             Object physics = rs.getObject("physics");
 92             Object chemistry = rs.getObject("chemistry");
 93             Object biology = rs.getObject("biology");
 94             System.out.println(id +","+ name +","+ age +","+ job+","+ chinese +","+ english +","+ math +","+ physics +","+ chemistry +","+biology);
 95         }
 96         
 97         rs.close();
 98         st.close();
 99         conn.close();
100     }
101 
102 }

九.JDBC的异常处理

 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:[email protected]
 5 */
 6 
 7 package cn.org.yinzhengjie.note;
 8 
 9 import java.sql.Connection;
10 import java.sql.DriverManager;
11 import java.sql.PreparedStatement;
12 import java.sql.SQLException;
13 import java.sql.Statement;
14 
15 public class ExceptionDemo {
16 
17     public static void main(String[] args) {
18         //提升作用域
19         Connection conn = null;
20         Statement st = null;
21 
22         try {
23             Class.forName("com.mysql.jdbc.Driver");
24 
25             conn = DriverManager.getConnection("jdbc:mysql://192.168.0.254:5200/yinzhengjie", "root", "yinzhengjie");
26 
27             String sql = "insert into classmate values (null,?,?,?,?,?,?,?,?,?)";
28 
29             PreparedStatement pst = conn.prepareStatement(sql);
30 
31             pst.setString(1, "杨明明");
32             pst.setInt(2, 32);
33             pst.setString(3, "网络工程师");
34             pst.setInt(4, 100);
35             pst.setInt(5, 98);
36             pst.setInt(6, 89);
37             pst.setInt(7, 86);
38             pst.setInt(8, 97);
39             pst.setInt(9, 94);
40 
41             int i = pst.executeUpdate();
42             // 判断插入语句是否执行成功
43             if (i != 0) {
44                 System.out.println("插入数据成功");
45             }
46 
47         } catch (ClassNotFoundException e) {
48             e.printStackTrace();
49         } catch (SQLException e) {
50             e.printStackTrace();
51         } finally {
52             //对被关闭的对象进行非空判断
53             try {
54                 if (st != null) {
55                     st.close();
56                 }
57             } catch (SQLException e) {
58                 e.printStackTrace();
59             }
60             try {
61                 if (conn != null) {
62                     conn.close();
63                 }
64             } catch (SQLException e) {
65                 e.printStackTrace();
66             }
67         }
68 
69     }
70 }
71 
72 /*
73 以上代码执行结果如下:
74 插入数据成功
75 */

十. JDBC操作较大数据对象

  如果存储的对象较大,我们可以采用以二进流的方式存储,即BLOB,如果你较大的文本文件的话也可以采用TEXT进行存储。值得一说的是,在测试建表的时候要注意字段的数据类型, 如果类型指定的过小的话可能导致数据存储会失败哟!

1>.准备实验环境

 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A/
 4 EMAIL:[email protected]
 5 */
 6 
 7 CREATE TABLE myblob(
 8     id INT PRIMARY KEY AUTO_INCREMENT,
 9     img LONGBLOB
10 );
11 
12 CREATE TABLE mytext(
13     id INT PRIMARY KEY AUTO_INCREMENT,
14     txt LONGBLOB
15 );

2>.JDBC操作BLOB对象

1 DriverName=com.mysql.jdbc.Driver
2 #zai "url" lu jing hou jia "?useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true" ke yi kai qi pi chu li mo shi !
3 url=jdbc:mysql://192.168.0.254:5200/yinzhengjie?useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true
4 user=root
5 password=yinzhengjie
config.properties 文件内容
 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:[email protected]
 5 */
 6 
 7 package cn.org.yinzhengjie.note;
 8 
 9 import java.sql.Connection;
10 import java.sql.DriverManager;
11 import java.util.ResourceBundle;
12 
13 /*
14  * 获取数据库连接的工具类
15  * 在获取连接对象的方法中,首先是注册驱动,实际上没有必要
16  * 注册驱动只需要执行一次就OK
17  * 
18  */
19 public class Utils {
20     
21     private Utils(){}
22     
23     private static final String DRIVERCLASS;
24     private static final String URL;
25     private static final String USERNAME;
26     private static final String PASSWORD;
27     //使用配置文件
28     static {
29         //注意,这里写文件名的时候不要写全称,我们此处这需要写前缀就好,在Windows操作系统中如果你画蛇添足写上了文件名后缀可能会报错哟!
30         DRIVERCLASS = ResourceBundle.getBundle("config").getString("DriverName");
31         URL = ResourceBundle.getBundle("config").getString("url");
32         USERNAME = ResourceBundle.getBundle("config").getString("user");
33         PASSWORD = ResourceBundle.getBundle("config").getString("password");
34     }
35     
36     //注册驱动
37     static{
38         //注册驱动
39         try {
40             Class.forName(DRIVERCLASS);
41         } catch (ClassNotFoundException e) {
42             e.printStackTrace();
43         }
44     }
45     
46     public static Connection getConnect() throws Exception{
47         
48         //获取连接
49         Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
50         return conn;
51     }
52 
53 }
Utils.java 文件内容
 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:[email protected]
 5 */
 6 
 7 package cn.org.yinzhengjie.note;
 8 
 9 import java.io.File;
10 import java.io.FileInputStream;
11 import java.io.FileNotFoundException;
12 import java.io.FileOutputStream;
13 import java.io.InputStream;
14 import java.sql.Connection;
15 import java.sql.PreparedStatement;
16 import java.sql.ResultSet;
17 import java.sql.SQLException;
18 
19 public class BlobDemo {
20 
21     public static void main(String[] args) throws Exception {
22 //        sava();
23         get();
24     }
25 
26     //获取二进制大对象
27     private static void get() throws Exception {
28         Connection conn = Utils.getConnect();
29         String sql = "select img from myblob where id = 1";
30         PreparedStatement ps = conn.prepareStatement(sql);
31         ResultSet rs = ps.executeQuery();
32         if(rs.next()){
33             InputStream in = rs.getBinaryStream(1);
34             FileOutputStream fos = new FileOutputStream("1.jpg");
35             byte[] buf = new byte[4096];
36             int len;
37             while((len = in.read(buf))!=-1){
38                 fos.write(buf,0,len);
39             }
40             fos.close();
41             in.close();
42         }
43         rs.close();
44         ps.close();
45         conn.close();
46     }
47 
48     
49     
50     //保存二进制流文件到数据库
51     private static void sava() throws Exception, SQLException, FileNotFoundException {
52         Connection conn = Utils.getConnect();
53         String sql = "insert into myblob values(null,?)";
54         
55         PreparedStatement ps = conn.prepareStatement(sql);
56 //        ps.setBinaryStream(1, new FileInputStream("c:/dog.jpg"));    //MySQL对这种方式传参不感冒!但是提供了其他方法进行传值!
57         File file = new File("C:/Users/yinzhengjie/Desktop/电子相册/1.jpg");
58         FileInputStream fis = new FileInputStream(file);
59         //将图片保存到数据库服务器中!
60         ps.setBinaryStream(1, fis, (int)file.length());        
61         
62         int i = ps.executeUpdate();
63         System.out.println(i);
64 
65         ps.close();
66         conn.close();
67     }
68 }
69 
70 
71 
72 /*
73 注意,如果出现以下报错的话,说明你上传的数据大于数据库定义的数据类型了哟!解决方法要么就是上传数据库规定的大小范围,要么修改数据库字段类型的限制范围。
74 com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'img' at row 1
75     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2983)*/

3>.JDBC操作TEXT对象

1 DriverName=com.mysql.jdbc.Driver
2 #zai "url" lu jing hou jia "?useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true" ke yi kai qi pi chu li mo shi !
3 url=jdbc:mysql://192.168.0.254:5200/yinzhengjie?useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true
4 user=root
5 password=yinzhengjie
config.properties 文件内容
 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:[email protected]
 5 */
 6 
 7 package cn.org.yinzhengjie.note;
 8 
 9 import java.sql.Connection;
10 import java.sql.DriverManager;
11 import java.util.ResourceBundle;
12 
13 /*
14  * 获取数据库连接的工具类
15  * 在获取连接对象的方法中,首先是注册驱动,实际上没有必要
16  * 注册驱动只需要执行一次就OK
17  * 
18  */
19 public class Utils {
20     
21     private Utils(){}
22     
23     private static final String DRIVERCLASS;
24     private static final String URL;
25     private static final String USERNAME;
26     private static final String PASSWORD;
27     //使用配置文件
28     static {
29         //注意,这里写文件名的时候不要写全称,我们此处这需要写前缀就好,在Windows操作系统中如果你画蛇添足写上了文件名后缀可能会报错哟!
30         DRIVERCLASS = ResourceBundle.getBundle("config").getString("DriverName");
31         URL = ResourceBundle.getBundle("config").getString("url");
32         USERNAME = ResourceBundle.getBundle("config").getString("user");
33         PASSWORD = ResourceBundle.getBundle("config").getString("password");
34     }
35     
36     //注册驱动
37     static{
38         //注册驱动
39         try {
40             Class.forName(DRIVERCLASS);
41         } catch (ClassNotFoundException e) {
42             e.printStackTrace();
43         }
44     }
45     
46     public static Connection getConnect() throws Exception{
47         
48         //获取连接
49         Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
50         return conn;
51     }
52 
53 }
Utils.java 文件内容
 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:[email protected]
 5 */
 6 package cn.org.yinzhengjie.note;
 7 
 8 import java.io.File;
 9 import java.io.FileInputStream;
10 import java.io.FileOutputStream;
11 import java.io.InputStream;
12 import java.sql.Connection;
13 import java.sql.PreparedStatement;
14 import java.sql.ResultSet;
15 
16 public class TextDemo {
17 
18     public static void main(String[] args) throws Exception {
19 //        textSava();
20         textGet();
21     }
22 
23     private static void textGet() throws Exception {
24         Connection conn = Utils.getConnect();
25         String sql = "select txt from mytext where id = 1";
26         PreparedStatement ps = conn.prepareStatement(sql);
27         ResultSet rs = ps.executeQuery();
28         if(rs.next()){
29             InputStream in = rs.getBinaryStream(1);
30             FileOutputStream fos = new FileOutputStream("1.txt");
31             byte[] buf = new byte[4096];
32             int len;
33             while((len = in.read(buf))!=-1){
34                 fos.write(buf,0,len);
35             }
36             fos.close();
37             in.close();
38         }
39         rs.close();
40         ps.close();
41         conn.close();
42     }
43 
44     private static void textSava() throws Exception {
45         Connection conn = Utils.getConnect();
46         String sql = "insert into mytext values(null,?)";
47         
48         PreparedStatement ps = conn.prepareStatement(sql);
49         File file = new File("C:/Users/yinzhengjie/Desktop/Java常见的关键字.txt");
50         FileInputStream fis = new FileInputStream(file);
51         //将图片保存到数据库服务器中!
52         ps.setBinaryStream(1, fis, (int)file.length());        
53         
54         int i = ps.executeUpdate();
55         System.out.println(i);
56 
57         ps.close();
58         conn.close();
59         
60         
61     }
62     
63 }
64     

十一.JDBC批处理案例

1>.准备实验环境

 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A/
 4 EMAIL:[email protected]
 5 */
 6 
 7 CREATE TABLE test1(
 8     id INT PRIMARY KEY AUTO_INCREMENT,
 9     num int
10 );

2>.批处理操作

 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A/
 4 EMAIL:[email protected]
 5 */
 6 
 7 CREATE TABLE test1(
 8     id INT PRIMARY KEY AUTO_INCREMENT,
 9     num int
10 );
config.propreties 文件内容
 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:[email protected]
 5 */
 6 
 7 package cn.org.yinzhengjie.note;
 8 
 9 import java.sql.Connection;
10 import java.sql.DriverManager;
11 import java.util.ResourceBundle;
12 
13 /*
14  * 获取数据库连接的工具类
15  * 在获取连接对象的方法中,首先是注册驱动,实际上没有必要
16  * 注册驱动只需要执行一次就OK
17  * 
18  */
19 public class Utils {
20     
21     private Utils(){}
22     
23     private static final String DRIVERCLASS;
24     private static final String URL;
25     private static final String USERNAME;
26     private static final String PASSWORD;
27     //使用配置文件
28     static {
29         //注意,这里写文件名的时候不要写全称,我们此处这需要写前缀就好,在Windows操作系统中如果你画蛇添足写上了文件名后缀可能会报错哟!
30         DRIVERCLASS = ResourceBundle.getBundle("config").getString("DriverName");
31         URL = ResourceBundle.getBundle("config").getString("url");
32         USERNAME = ResourceBundle.getBundle("config").getString("user");
33         PASSWORD = ResourceBundle.getBundle("config").getString("password");
34     }
35     
36     //注册驱动
37     static{
38         //注册驱动
39         try {
40             Class.forName(DRIVERCLASS);
41         } catch (ClassNotFoundException e) {
42             e.printStackTrace();
43         }
44     }
45     
46     public static Connection getConnect() throws Exception{
47         
48         //获取连接
49         Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
50         return conn;
51     }
52 
53 }
Utils.java 文件内容
 1 /*
 2 @author :yinzhengjie
 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
 4 EMAIL:[email protected]
 5 */
 6 package cn.org.yinzhengjie.note;
 7 
 8 import java.sql.Connection;
 9 import java.sql.PreparedStatement;
10 import java.sql.SQLException;
11 import java.sql.Statement;
12 
13 /*
14  * 1.驱动版本5.1.13以上
15  * 2.在url中开启批处理功能
16  */
17 public class BatchTest {
18 
19     public static void main(String[] args) throws Exception {
20         test1();        //3526毫秒
21 //        test2();        //用时1523毫秒
22     }
23     
24 
25     //5.1.13之后批处理功能,SQL语句的整体框架变动起来很方便!
26     private static void test1() throws Exception, SQLException {
27         Connection conn = Utils.getConnect();
28         Statement st = conn.createStatement();
29         long start = System.currentTimeMillis();
30         for(int i = 0;i<100000;i++){
31             String sql = "insert into test1 values(null," + i + ")";
32             st.addBatch(sql);
33         }
34         
35         st.executeBatch();
36         st.clearBatch();
37         st.close();
38         conn.close();
39         System.out.println(System.currentTimeMillis() - start);
40     }
41     
42     //SQL语句的整体框架变动起来麻烦,需要逐个进行预编译
43     private static void test2() throws Exception, SQLException {
44         Connection conn = Utils.getConnect();
45         String sql = "insert into test1 values(null,?)";
46         PreparedStatement ps = conn.prepareStatement(sql);
47         long start = System.currentTimeMillis();
48         
49         for(int i = 1;i<=100000;i++){
50             ps.setInt(1, i);
51             if(i % 1000 == 0){
52                 ps.executeBatch();
53                 ps.clearBatch();
54             }
55             ps.addBatch();
56         }
57         
58         ps.executeBatch();
59         ps.clearBatch();
60         ps.close();
61         conn.close();
62         System.out.println(System.currentTimeMillis() - start);
63     }
64 
65 }

猜你喜欢

转载自www.cnblogs.com/yinzhengjie/p/9022164.html
222