JDBC连接与自定义线程池

版本1

 1 package jdbc_utils;
 2
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.sql.Statement;
 8
 9 import org.junit.Test;
10 /**
11  *     获取Connection对象
12  *     方案一 :简单版,直接把配置信息写在代码中
13  *
14  *
15  */
16
17
18 public class JDBCUtils_V1 {
19     public static final String url = "jdbc:mysql://localhost:3306/web08";
20     public static final String username = "root";
21     public static final String password = "123";
22     @Test
23     public static Connection getConnection() {
24 //        1.注册驱动
25         try {
26             Class.forName("com.mysql.jdbc.Driver");
27
28 //        2.获取连接
29             Connection conn = DriverManager.getConnection(url,username,password);
30 //        3.    返回连接对象
31             System.out.println(conn);
32             return conn;
33         } catch (Exception e) {
34             // TODO Auto-generated catch block
35             e.printStackTrace();
36             throw new RuntimeException(e);
37         }
38
39     }
40
41     public static void release(Connection conn,Statement stat,ResultSet rs) {
42         if(rs!=null) {
43             try {
44                 rs.close();
45             } catch (SQLException e) {
46                 // TODO Auto-generated catch block
47                 e.printStackTrace();
48             }finally {
49
50                 if(stat!=null) {
51                     try {
52                         stat.close();
53                     } catch (SQLException e) {
54                         // TODO Auto-generated catch block
55                         e.printStackTrace();
56                     }finally {
57
58                         if(conn!=null) {
59                             try {
60                                 conn.close();
61                             } catch (SQLException e) {
62                                 // TODO Auto-generated catch block
63                                 e.printStackTrace();
64                             }
65                         }
66                     }
67                 }
68             }
69         }
70     }
71 }

版本2:

 1 package jdbc_utils;
 2
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.sql.Statement;
 8 import java.util.ResourceBundle;
 9
10 import org.junit.Test;
11 /**
12  *
13  * 方案二:配置信息写入文件,采用ResourceBundle的对象,获取文件中的pro.properties的值
14  *
15  */
16 public class JDBCUtils_V2 {
17     private static String driver;
18     private static String url;
19     private static String username ;
20     private static String password ;
21     @Test
22     public static Connection getConnection() {
23 /**
24  *         加载pro.properties配置文件
25  *         这里采用ResourceBundle
26  */
27         ResourceBundle bundle = ResourceBundle.getBundle("pro");
28         driver=bundle.getString("driver");//注意这里的driver需要"",看了好久才发现,哎
29         url=bundle.getString("url");
30         username=bundle.getString("username");
31         password = bundle.getString("password");
32         System.out.println(driver);
33 //        1.注册驱动
34         try {
35             Class.forName(driver);
36 //        2.获取连接
37             Connection conn = DriverManager.getConnection(url,username,password);
38 //        3.    返回连接对象
39             return conn;
40         } catch (Exception e) {
41             e.printStackTrace();
42             throw new RuntimeException(e);
43         }
44
45     }
46
47     public static void release(Connection conn,Statement stat,ResultSet rs) {
48         if(rs!=null) {
49             try {
50                 rs.close();
51             } catch (SQLException e) {
52                 e.printStackTrace();
53             }finally {
54
55                 if(stat!=null) {
56                     try {
57                         stat.close();
58                     } catch (SQLException e) {
59
60                         e.printStackTrace();
61                     }finally {
62
63                         if(conn!=null) {
64                             try {
65                                 conn.close();
66                             } catch (SQLException e) {
67
68                                 e.printStackTrace();
69                             }
70                         }
71                     }
72                 }
73             }
74         }
75     }
76 }

版本3:

 1 package jdbc_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  *         加载pro.properties配置文件
13  *         这里采用反射,类加载器,获取资源流
14  */
15 public class JDBCUtils_V3 {
16     private static String driver;
17     private static String url;
18     private static String username ;
19     private static String password ;
20
21     public static Connection getConnection() {
22
23         try {
24         InputStream in=JDBCUtils_V3.class.getClassLoader().getResourceAsStream("pro.properties");
25         Properties props = new Properties();
26         props.load(in);
27
28
29         driver=props.getProperty("driver");
30         url=props.getProperty("url");
31         username=props.getProperty("username");
32         password =props.getProperty("password");
33         }catch(Exception e) {
34             System.err.println(e);
35             throw new RuntimeException(e);
36         }
37 //        1.注册驱动
38         try {
39             Class.forName(driver);
40 //        2.获取连接
41             Connection conn = DriverManager.getConnection(url,username,password);
42 //        3.    返回连接对象
43             return conn;
44         } catch (Exception e) {
45             // TODO Auto-generated catch block
46             e.printStackTrace();
47             throw new RuntimeException(e);
48         }
49
50     }
51
52     public static void release(Connection conn,Statement stat,ResultSet rs) {
53         if(rs!=null) {
54             try {
55                 rs.close();
56             } catch (SQLException e) {
57                 // TODO Auto-generated catch block
58                 e.printStackTrace();
59             }finally {
60
61                 if(stat!=null) {
62                     try {
63                         stat.close();
64                     } catch (SQLException e) {
65                         // TODO Auto-generated catch block
66                         e.printStackTrace();
67                     }finally {
68
69                         if(conn!=null) {
70                             try {
71                                 conn.close();
72                             } catch (SQLException e) {
73                                 // TODO Auto-generated catch block
74                                 e.printStackTrace();
75                             }
76                         }
77                     }
78                 }
79             }
80         }
81     }
82 }

配置文件pro.properties

1 driver=com.mysql.jdbc.Driver
2 url=jdbc:mysql://localhost:3306/web08?useUnicode=true&characterEncoding=utf8
3 username=root
4 password=123

自定义连接池

  1 package datasource;
  2
  3 import java.io.PrintWriter;
  4 import java.sql.Connection;
  5 import java.sql.SQLException;
  6 import java.sql.SQLFeatureNotSupportedException;
  7 import java.util.LinkedList;
  8 import java.util.logging.Logger;
  9
 10 import javax.sql.DataSource;
 11
 12 import jdbc_utils.JDBCUtils_V1;
 13 import jdbc_utils.JDBCUtils_V2;
 14 import jdbc_utils.JDBCUtils_V3;
 15
 16 public class MyDataSource implements DataSource {
 17     private  Connection conn;
 18
 19     //1.创建一个容器存放连接对象Connection
 20     private static LinkedList<Connection> pool = new LinkedList<Connection>();
 21
 22     //循环为pool添加5个连接对象
 23
 24     static{
 25             for(int i = 0; i < 5; i++) {
 26             Connection    conn = JDBCUtils_V3.getConnection();
 27
 28                 pool.add(conn);
 29             }
 30
 31     }
 32     public MyDataSource() {
 33
 34     }
 35     public MyDataSource(Connection conn) {
 36         this.conn=conn;
 37     }
 38     public Connection getConnection() throws SQLException {
 39         if(pool.isEmpty()) {
 40             for(int i = 0; i < 5; i++) {
 41                 conn = JDBCUtils_V2.getConnection();
 42                 pool.add(conn);
 43             }
 44         }
 45         conn=pool.removeFirst();
 46         return conn;
 47     }
 48
 49     public void backConnection(Connection conn) {
 50         pool.add(conn);
 51     }
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61     @Override
 62     public PrintWriter getLogWriter() throws SQLException {
 63         // TODO Auto-generated method stub
 64         return null;
 65     }
 66
 67     @Override
 68     public int getLoginTimeout() throws SQLException {
 69         // TODO Auto-generated method stub
 70         return 0;
 71     }
 72
 73     @Override
 74     public Logger getParentLogger() throws SQLFeatureNotSupportedException {
 75         // TODO Auto-generated method stub
 76         return null;
 77     }
 78
 79     @Override
 80     public void setLogWriter(PrintWriter arg0) throws SQLException {
 81         // TODO Auto-generated method stub
 82
 83     }
 84
 85     @Override
 86     public void setLoginTimeout(int arg0) throws SQLException {
 87         // TODO Auto-generated method stub
 88
 89     }
 90
 91     @Override
 92     public boolean isWrapperFor(Class<?> arg0) throws SQLException {
 93         // TODO Auto-generated method stub
 94         return false;
 95     }
 96
 97     @Override
 98     public <T> T unwrap(Class<T> arg0) throws SQLException {
 99         // TODO Auto-generated method stub
100         return null;
101     }
102
103
104
105     @Override
106     public Connection getConnection(String arg0, String arg1) throws SQLException {
107         // TODO Auto-generated method stub
108         return null;
109     }
110
111 }

测试demo

 1 package datasource;
 2
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5
 6 import org.junit.Test;
 7
 8 public class TestMyDataSource {
 9
10     @Test
11     public void testAddUser() {
12             Connection conn = null;
13             PreparedStatement pstmt= null;
14             MyDataSource datasource = new MyDataSource();
15             System.out.println(datasource);
16             try {
17                 conn = datasource.getConnection();
18                 String sql = "insert into tbl_user values(null,?,?)";
19                 pstmt =  conn.prepareStatement(sql);
20                 pstmt.setString(1, "hello");
21                 pstmt.setString(2, "java");
22                 int row=pstmt.executeUpdate();
23                 if(row>0) {
24                     System.out.println("添加成功");
25                 }else {
26                     System.out.println("添加失败");
27                 }
28             }catch(Exception e) {
29                 throw new RuntimeException(e);
30             }finally {
31                 datasource.backConnection(conn);
32             }
33
34     }
35 }

JDBC连接需要导包   mysql-connector-java-5.1.37.jar    不然会报找不到Class异常

时间: 2024-08-01 02:59:09

JDBC连接与自定义线程池的相关文章

c#网络通信框架networkcomms内核解析之十 支持优先级的自定义线程池

本例基于networkcomms2.3.1开源版本  gplv3协议 如果networkcomms是一顶皇冠,那么CommsThreadPool(自定义线程池)就是皇冠上的明珠了,这样说应该不夸张的,她那么优美,简洁,高效. 在 <c#网络通信框架networkcomms内核解析之六 处理接收到的二进制数据>中我们曾经提到,服务器收到数据后,如果是系统内部保留类型数据或者是最高优先级数据,系统会在主线程中处理,其他的会交给自定义线程池进行处理. 作为服务器,处理成千上万的连接及数据,单线程性能

使用自定义线程池优化EchoServer

在上一篇文章中http://www.cnblogs.com/gosaint/p/8494423.html 我自定义了线程池ThreadPool.现在在我的EchoServer中使用自定义线程池去负责和客户端的通讯,代码如下所示: package com.asiaInfo.caozg.ch_03.threadPool; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; imp

池化技术——自定义线程池

目录 池化技术--自定义线程池 1.为什么要使用线程池? 1.1.池化技术的特点: 1.2.线程池的好处: 1.3.如何自定义一个线程池 2.三大方法 2.1.单个线程的线程池方法 2.2.固定的线程池的大小的方法 2.3.可伸缩的线程池的方法 2.4.完整的测试代码为: 3.为什么要自定义线程池?三大方法创建线程池的弊端分析 4.七大参数 5.如何手动的去创建一个线程池 6.四种拒绝策略 6.1.会抛出异常的拒绝策略 6.2.哪来的去哪里拒绝策略 6.3.丢掉任务拒绝策略 6.4.尝试竞争拒绝

java多线程(四)-自定义线程池

当我们使用 线程池的时候,可以使用 newCachedThreadPool()或者 newFixedThreadPool(int)等方法,其实我们深入到这些方法里面,就可以看到它们的是实现方式是这样的. 1 public static ExecutorService newCachedThreadPool() { 2 return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 3 60L, TimeUnit.SECONDS, 4 new Synchro

Java自定义线程池详解

自定义线程池的核心:ThreadPoolExecutor 为了更好的控制多线程,JDK提供了一套线程框架Executor,帮助开发人员有效的进行线程控制,其中在java.util.concurrent包下,是JDK并发包的核心,比如我们熟知的Executors.Executors扮演着线程工厂的角色,我们通过它可以创建特定功能的线程池,而这些线程池背后的就是:ThreadPoolExecutor.那么下面我们来具体分析下它. 构造ThreadPoolExecutor public ThreadP

自定义线程池

线程池: 自定义线程池一: #!/usr/bin/env python # -*- coding:utf-8 -*- import Queue import threading class ThreadPool(object): def __init__(self, max_num=20): self.queue = Queue.Queue(max_num) for i in xrange(max_num): self.queue.put(threading.Thread) def get_th

JAVA并发,线程工厂及自定义线程池

1 package com.xt.thinks21_2; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 import java.util.concurrent.SynchronousQueue; 6 import java.util.concurrent.ThreadFactory; 7 import java.util.concurrent.ThreadPo

使用Lock(ReentrantLock)结合Condition实现自定义线程池

声明: 1.该篇只是提供一种自定义线程池的实现方式,可能性能.安全等方面需要优化: 2.该篇自定义线程池使用Lock(可重入锁ReentrantLock)结合Condition来实现: 3.该篇力求使用简单的方式呈现,如有错误之处,欢迎指正,在此表示感谢. 概述 自定义线程池三要素包括: 1.存储线程的容器(或叫线程池).该容器可使用数组或链表,容器中存放执行线程,本篇使用链表实现. 2.执行线程(或叫执行器).具体执行的线程. 3.执行任务.执行线程需要执行的具体任务. 代码 /** * 任务

Android 自定义线程池的实战

前言:在上一篇文章中我们讲到了AsyncTask的基本使用.AsyncTask的封装.AsyncTask 的串行/并行线程队列.自定义线程池.线程池的快速创建方式. 对线程池不了解的同学可以先看 Android AsyncTask 深度理解.简单封装.任务队列分析.自定义线程池 ------------------------------------------------------------------------------------------------------- 1.Exec