苦尽甘来 一个月学通JavaWeb(四十 数据库)

夜光序言:

世界上最遥远的距离

不是生与死

而是你就站在我面前

我却无法说出我爱你~~

 

 

 

正文:

1 C3P0简介

C3P0也是开源免费的连接池

 

C3P0被很多人看好

 

2 C3P0的使用

C3P0中池类是:ComboPooledDataSource。

1 C3P0简介

C3P0也是开源免费的连接池!C3P0被很多人看好!

 

2 C3P0的使用

C3P0中池类是:ComboPooledDataSource。

public void fun1() throws PropertyVetoException, SQLException {

ComboPooledDataSource ds = new ComboPooledDataSource();

ds.setJdbcUrl("jdbc:mysql://localhost:3306/mydb1");

ds.setUser("root");

ds.setPassword("123");

ds.setDriverClass("com.mysql.jdbc.Driver");

 

ds.setAcquireIncrement(5);

ds.setInitialPoolSize(20);

ds.setMinPoolSize(2);

ds.setMaxPoolSize(50);

 

Connection con = ds.getConnection();

System.out.println(con);

con.close();

}

 

配置文件要求:

  1. 文件名称:必须叫c3p0-config.xml
  2. 文件位置:必须在src下

 

 

c3p0也可以指定配置文件,而且配置文件可以是properties,也可骒xml的。当然xml的高级一些了。但是c3p0的配置文件名必须为c3p0-config.xml,并且必须放在类路径下。

<?xml version="1.0" encoding="UTF-8"?>

<c3p0-config>

<default-config>

<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>

<property name="driverClass">com.mysql.jdbc.Driver</property>

<property name="user">root</property>

<property name="password">123</property>

<property name="acquireIncrement">3</property>

<property name="initialPoolSize">10</property>

<property name="minPoolSize">2</property>

<property name="maxPoolSize">10</property>

</default-config>

<named-config name="oracle-config">

<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>

<property name="driverClass">com.mysql.jdbc.Driver</property>

<property name="user">root</property>

<property name="password">123</property>

<property name="acquireIncrement">3</property>

<property name="initialPoolSize">10</property>

<property name="minPoolSize">2</property>

<property name="maxPoolSize">10</property>

</named-config>

</c3p0-config>

 

c3p0的配置文件中可以配置多个连接信息,可以给每个配置起个名字,这样可以方便的通过配置名称来切换配置信息。上面文件中默认配置为mysql的配置,名为oracle-config的配置也是mysql的配置,呵呵。

public void fun2() throws PropertyVetoException, SQLException {

ComboPooledDataSource ds = new ComboPooledDataSource();

Connection con = ds.getConnection();

System.out.println(con);

con.close();

}

public void fun2() throws PropertyVetoException, SQLException {

ComboPooledDataSource ds = new ComboPooledDataSource("orcale-config");

Connection con = ds.getConnection();

System.out.println(con);

con.close();

}

 

Tomcat配置连接池

 

1 Tomcat配置JNDI资源

JNDI(Java Naming and Directory Interface),Java命名和目录接口。JNDI的作用就是:在服务器上配置资源,然后通过统一的方式来获取配置的资源。

我们这里要配置的资源当然是连接池了,这样项目中就可以通过统一的方式来获取连接池对象了。

 

 

配置JNDI资源需要到<Context>元素中配置<Resource>子元素:

  1. name:指定资源的名称,这个名称可以随便给,在获取资源时需要这个名称;
  2. factory:用来创建资源的工厂,这个值基本上是固定的,不用修改;
  3. type:资源的类型,我们要给出的类型当然是我们连接池的类型了;
  4. bar:表示资源的属性,如果资源存在名为bar的属性,那么就配置bar的值。对于DBCP连接池而言,你需要配置的不是bar,因为它没有bar这个属性,而是应该去配置url、username等属性。

 

<Context>  

  <Resource name="mydbcp"

type="org.apache.tomcat.dbcp.dbcp.BasicDataSource"

factory="org.apache.naming.factory.BeanFactory"

username="root"

password="123"

driverClassName="com.mysql.jdbc.Driver"    

url="jdbc:mysql://127.0.0.1/mydb1"

maxIdle="3"

maxWait="5000"

maxActive="5"

initialSize="3"/>

</Context>  

<Context>  

  <Resource name="myc3p0"

type="com.mchange.v2.c3p0.ComboPooledDataSource"

factory="org.apache.naming.factory.BeanFactory"

user="root"

password="123"

classDriver="com.mysql.jdbc.Driver"    

jdbcUrl="jdbc:mysql://127.0.0.1/mydb1"

maxPoolSize="20"

minPoolSize ="5"

initialPoolSize="10"

acquireIncrement="2"/>

</Context>  

 

配置文件要求:

  1. 文件名称:必须叫c3p0-config.xml
  2. 文件位置:必须在src下

 

 

c3p0也可以指定配置文件,而且配置文件可以是properties,也可骒xml的。当然xml的高级一些了。但是c3p0的配置文件名必须为c3p0-config.xml,并且必须放在类路径下。

<?xml version="1.0" encoding="UTF-8"?>

<c3p0-config>

<default-config>

<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>

<property name="driverClass">com.mysql.jdbc.Driver</property>

<property name="user">root</property>

<property name="password">123</property>

<property name="acquireIncrement">3</property>

<property name="initialPoolSize">10</property>

<property name="minPoolSize">2</property>

<property name="maxPoolSize">10</property>

</default-config>

<named-config name="oracle-config">

<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>

<property name="driverClass">com.mysql.jdbc.Driver</property>

<property name="user">root</property>

<property name="password">123</property>

<property name="acquireIncrement">3</property>

<property name="initialPoolSize">10</property>

<property name="minPoolSize">2</property>

<property name="maxPoolSize">10</property>

</named-config>

</c3p0-config>

 

c3p0的配置文件中可以配置多个连接信息,可以给每个配置起个名字,这样可以方便的通过配置名称来切换配置信息。

上面文件中默认配置为mysql的配置,名为oracle-config的配置也是mysql的配置,嘿哈。

public void fun2() throws PropertyVetoException, SQLException {

ComboPooledDataSource ds = new ComboPooledDataSource();

Connection con = ds.getConnection();

System.out.println(con);

con.close();

}

public void fun2() throws PropertyVetoException, SQLException {

ComboPooledDataSource ds = new ComboPooledDataSource("orcale-config");

Connection con = ds.getConnection();

System.out.println(con);

con.close();

}

 

修改JdbcUtils

因为已经学习了连接池,那么JdbcUtils的获取连接对象的方法也要修改一下了。

JdbcUtils.java

public class JdbcUtils {

private static DataSource dataSource = new ComboPooledDataSource();

 

public static DataSource getDataSource() {

return dataSource;

}

 

public static Connection getConnection() {

try {

return dataSource.getConnection();

} catch (Exception e) {

throw new RuntimeException(e);

}

}

}

 

ThreadLocal

 

Thread à 人类

Runnable à 任务类

 

 

key

value

thread1

aaa

thread2

bbb

thread3

ccc

 

1 ThreadLocal API

ThreadLocal类只有三个方法:

  1. void set(T value):保存值;
  2. T get():获取值;
  3. void remove():移除值。

 

2 ThreadLocal的内部是Map

ThreadLocal内部其实是个Map来保存数据。虽然在使用ThreadLocal时只给出了值,没有给出键,其实它内部使用了当前线程做为键。

class MyThreadLocal<T> {

private Map<Thread,T> map = new HashMap<Thread,T>();

public void set(T value) {

map.put(Thread.currentThread(), value);

}

 

public void remove() {

map.remove(Thread.currentThread());

}

 

public T get() {

return map.get(Thread.currentThread());

}

}

 

 

1 BaseServlet的作用

 

在开始客户管理系统之前,我们先写一个工具类:BaseServlet。

我们知道,写一个项目可能会出现N多个Servlet,而且一般一个Servlet只有一个方法(doGet或doPost),如果项目大一些,那么Servlet的数量就会很惊人。

为了避免Servlet的“膨胀”,我们写一个BaseServlet。

它的作用是让一个Servlet可以处理多种不同的请求。

不同的请求调用Servlet的不同方法。

我们写好了BaseServlet后,让其他Servlet继承BaseServlet,

例如CustomerServlet继承BaseServlet,然后在CustomerServlet中提供add()、update()、delete()等方法,每个方法对应不同的请求。

 

2 BaseServlet分析

我们知道,Servlet中处理请求的方法是service()方法,这说明我们需要让service()方法去调用其他方法。例如调用add()、mod()、del()、all()等方法~

具体调用哪个方法需要在请求中给出方法名称~~

 

然后service()方法通过方法名称来调用指定的方法。

无论是点击超链接,还是提交表单,请求中必须要有method参数,这个参数的值就是要请求的方法名称,这样BaseServlet的service()才能通过方法名称来调用目标方法。例如某个链接如下:

<a href=”/xxx/CustomerServlet?method=add”>添加Genius</a>

 

3 BaseServlet代码

public class BaseServlet extends HttpServlet {

/*

 * 它会根据请求中的m,来决定调用本类的哪个方法

 */

protected void service(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

req.setCharacterEncoding("UTF-8");

res.setContentType("text/html;charset=utf-8");

 

// 例如:http://localhost:8080/demo1/xxx?m=add

String methodName = req.getParameter("method");// 它是一个方法名称

 

// 当没用指定要调用的方法时,那么默认请求的是execute()方法。

if(methodName == null || methodName.isEmpty()) {

methodName = "execute";

}

Class c = this.getClass();

try {

// 通过方法名称获取方法的反射对象

Method m = c.getMethod(methodName, HttpServletRequest.class,

HttpServletResponse.class);

// 反射方法目标方法,也就是说,如果methodName为add,那么就调用add方法。

String result = (String) m.invoke(this, req, res);

// 通过返回值完成请求转发

if(result != null && !result.isEmpty()) {

req.getRequestDispatcher(result).forward(req, res);

}

} catch (Exception e) {

throw new ServletException(e);

}

}

}

 

DBUtils

 

1 DBUtils简介

DBUtils是Apache Commons组件中的一员,开源免费~~

DBUtils是对JDBC的简单封装

但是它还是被很多公司使用

DBUtils的Jar包:dbutils.jar

 

2 DBUtils主要类

  1. DbUtils:都是静态方法,一系列的close()方法;
  2. QueryRunner:
  • update():执行insert、update、delete;
  • query():执行select语句;
  • batch():执行批处理。

 

3 QueryRunner之更新

QueryRunner的update()方法可以用来执行insert、update、delete语句。

创建QueryRunner

构造器:QueryRunner();

 

update()方法

int update(Connection con, String sql, Object… params)

 

@Test

public void fun1() throws SQLException {

QueryRunner qr = new QueryRunner();

String sql = "insert into user values(?,?,?)";

qr.update(JdbcUtils.getConnection(), sql, "u1", "zhangSan", "123");

}

 

还有另一种方式来使用QueryRunner

创建QueryRunner

构造器:QueryRunner(DataSource)

 

update()方法

int update(String sql, Object… params)

 

这种方式在创建QueryRunner时传递了连接池对象,那么在调用update()方法时就不用再传递Connection了。

@Test

public void fun2() throws SQLException {

QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());

String sql = "insert into user values(?,?,?)";

qr.update(sql, "u1", "A", "123");

}

 

4 ResultSetHandler

我们知道在执行select语句之后得到的是ResultSet,然后我们还需要对ResultSet进行转换,得到最终我们想要的数据。你可以希望把ResultSet的数据放到一个List中,也可能想把数据放到一个Map中,或是一个Bean中。

DBUtils提供了一个接口ResultSetHandler,它就是用来ResultSet转换成目标类型的工具。你可以自己去实现这个接口,把ResultSet转换成你想要的类型。

DBUtils提供了很多个ResultSetHandler接口的实现,这些实现已经基本够用了,我们通常不用自己去实现ResultSet接口了。

  1. MapHandler:单行处理器!把结果集转换成Map<String,Object>,其中列名为键~~
  2. MapListHandler:多行处理器!把结果集转换成List<Map<String,Object>>;
  3. BeanHandler:单行处理器!把结果集转换成Bean,该处理器需要Class参数,即Bean的类型;
  4. BeanListHandler:多行处理器!把结果集转换成List<Bean>;
  5. ColumnListHandler:多行单列处理器~~把结果集转换成List<Object>,使用ColumnListHandler时需要指定某一列的名称或编号,例如:new ColumListHandler(“name”)表示把name列的数据放到List中。
  6. ScalarHandler:单行单列处理器!把结果集转换成Object。一般用于聚集查询,例如select count(*) from tab_student。

 

Map处理器

 

Bean处理器

 

Column处理器

Scalar处理器

 

5 QueryRunner之查询

QueryRunner的查询方法是:

public <T> T query(String sql, ResultSetHandler<T> rh, Object… params)

public <T> T query(Connection con, String sql, ResultSetHandler<T> rh, Object… params)

query()方法会通过sql语句和params查询出ResultSet,然后通过rh把ResultSet转换成对应的类型再返回。

 

@Test

public void fun1() throws SQLException {

DataSource ds = JdbcUtils.getDataSource();

QueryRunner qr = new QueryRunner(ds);

String sql = "select * from Genius_student where number=?";

Map<String,Object> map = qr.query(sql, new MapHandler(), "S_2000");

System.out.println(map);

}

 

@Test

public void fun2() throws SQLException {

DataSource ds = JdbcUtils.getDataSource();

QueryRunner qr = new QueryRunner(ds);

String sql = "select * from Genius_student";

List<Map<String,Object>> list = qr.query(sql, new MapListHandler());

for(Map<String,Object> map : list) {

System.out.println(map);

}

}

 

@Test

public void fun3() throws SQLException {

DataSource ds = JdbcUtils.getDataSource();

QueryRunner qr = new QueryRunner(ds);

String sql = "select * from Genius_student where number=?";

Student stu = qr.query(sql, new BeanHandler<Student>(Student.class), "S_2000");

System.out.println(stu);

}

 

@Test

public void fun4() throws SQLException {

DataSource ds = JdbcUtils.getDataSource();

QueryRunner qr = new QueryRunner(ds);

String sql = "select * from Genius_student";

List<Student> list = qr.query(sql, new BeanListHandler<Student>(Student.class));

for(Student stu : list) {

System.out.println(stu);

}

}

 

@Test

public void fun5() throws SQLException {

DataSource ds = JdbcUtils.getDataSource();

QueryRunner qr = new QueryRunner(ds);

String sql = "select * from Genius_student";

List<Object> list = qr.query(sql, new ColumnListHandler("name"));

for(Object s : list) {

System.out.println(s);

}

}

 

@Test

public void fun6() throws SQLException {

DataSource ds = JdbcUtils.getDataSource();

QueryRunner qr = new QueryRunner(ds);

String sql = "select count(*) from Genius_student";

Number number = (Number)qr.query(sql, new ScalarHandler());

int cnt = number.intValue();

System.out.println(cnt);

}

 

5 QueryRunner之批处理

QueryRunner还提供了批处理方法:batch()。

我们更新一行记录时需要指定一个Object[]为参数,如果是批处理,那么就要指定Object[][]为参数了。即多个Object[]就是Object[][]了,其中每个Object[]对应一行记录:

@Test

public void fun10() throws SQLException {

DataSource ds = JdbcUtils.getDataSource();

QueryRunner qr = new QueryRunner(ds);

String sql = "insert into Genius_student values(?,?,?,?)";

Object[][] params = new Object[10][];//表示 要插入10行记录

for(int i = 0; i < params.length; i++) {

params[i] = new Object[]{"S_300" + i, "name" + i, 30 + i, i%2==0?"男":"女"};

}

qr.batch(sql, params);

}

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值