1. 程式人生 > >使用c3p0連線資料庫實現增刪改查

使用c3p0連線資料庫實現增刪改查

學習spring之前,視訊中先給我們一個任務就是用c3p0連線資料庫來完成增刪改查

一,、準備     

  JAR包:

            既然是連線資料庫第一個最重要的就是資料庫的驅動包mysql-connection-java-5.1.44-bin.jar      

            接著就是C3P0-0.9.2.1.jar以及mchange-commons-java-0.2.3.4.jar

            然後還少不了dbutils 使用的是commons-dbutils-1.7.jar   

            一共是4個JAR包

二、配置 

   配置資料庫連線:

            建立c3p0-config.xml的配置檔案,裡面包含連線資料庫的資訊

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/mybatis</property>
		<property name="user">root</property>
		<property name="password">123</property>
		<property name="acquireIncrement">5</property>
		<property name="initialPoolSize">10</property>
		<property name="minPoolSize">5</property>
		<property name="maxPoolSize">20</property>
	</default-config>
</c3p0-config>

        建立C3P0Util.java 使用ComboPooledDataSource的物件獲取資料庫連線

package util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Util {

	private static ComboPooledDataSource ds=new ComboPooledDataSource();
	
	//獲取資料來源
	public static DataSource getDataSource(){
		return ds;
	}
	//獲取一個連線
	public static Connection getConnection() throws SQLException{
		return ds.getConnection();
	}
}

        由於沒有使用Mybatis的逆向工程,這裡需要手動建立Customer.java 用於獲取資料庫表的所有列

package domain;

import java.io.Serializable;

public class Customer implements Serializable{

		private int cust_id;
		private String cust_name;
		private String cust_source;
		private String cust_industry;
		private String cust_level;
		private String cust_address;
		private String cust_phone;
		public int getCust_id() {
			return cust_id;
		}
		public void setCust_id(int cust_id) {
			this.cust_id = cust_id;
		}
		public String getCust_name() {
			return cust_name;
		}
		public void setCust_name(String cust_name) {
			this.cust_name = cust_name;
		}
		public String getCust_source() {
			return cust_source;
		}
		public void setCust_source(String cust_source) {
			this.cust_source = cust_source;
		}
		public String getCust_industry() {
			return cust_industry;
		}
		public void setCust_industry(String cust_industry) {
			this.cust_industry = cust_industry;
		}
		public String getCust_level() {
			return cust_level;
		}
		public void setCust_level(String cust_level) {
			this.cust_level = cust_level;
		}
		public String getCust_address() {
			return cust_address;
		}
		public void setCust_address(String cust_address) {
			this.cust_address = cust_address;
		}
		public String getCust_phone() {
			return cust_phone;
		}
		public void setCust_phone(String cust_phone) {
			this.cust_phone = cust_phone;
		}
		@Override
		public String toString() {
			return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name
					+ ", cust_source=" + cust_source + ", cust_industry="
					+ cust_industry + ", cust_level=" + cust_level
					+ ", cust_address=" + cust_address + ", cust_phone="
					+ cust_phone + "]";
		}		
}

三、介面

    上面的配置檔案和資料庫表資訊檔案都已經寫好了,現在需要寫兩個介面提供所有的增刪改查的方法

    建立ICustomerDao.java 持久層介面 ,也就是最底層和資料庫連線的介面類

package dao;

import java.util.List;

import domain.Customer;

public interface ICustomerDao {

	List<Customer> findAllCustomer();

	void saveCustomer(Customer customer);

	void updateCustomer(Customer customer);

	void deleteCustomer(int custId);

	Customer findCustomerById(int custId);

}

    建立ICustomerService.java 業務層介面,用於持久層和客戶端連線的介面類,和Dao的方法一樣

package service;

import java.util.List;

import domain.Customer;

public interface ICustomerService {
		
	//查詢所有客戶
	List<Customer> findAllCustomer();
	//儲存客戶資訊
	void saveCustomer(Customer customer);
	//更改客戶資訊
	void updateCustomer(Customer customer);
	//根據Id刪除物件
	void deleteCustomer(int cust_id);
	//根據ID查詢使用者,返回使用者資訊
	Customer findCustomerById(int cust_id);
}

四、實現類

    建立CustomerDao.java 實現Dao介面,利用C3P0裡的QueryRunner類獲取到資料庫連線資訊連線資料庫

    並將SQL語句傳給資料庫然後得到SQL的返回值。

package dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import dao.ICustomerDao;
import domain.Customer;
import util.C3P0Util;

//客戶的持久層實現類
public class CustomerDao implements ICustomerDao {

	private QueryRunner runner=new QueryRunner(C3P0Util.getDataSource());
	@Override
	public List<Customer> findAllCustomer() {
		try {
			return runner.query("select * from cst_customer", new BeanListHandler<Customer>(Customer.class));
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void saveCustomer(Customer customer) {
		try {
			runner.update("insert into cst_customer(cust_name,cust_source,cust_industry,cust_level,cust_address,cust_phone)values(?,?,?,?,?,?)",
					customer.getCust_name(),customer.getCust_source(),customer.getCust_industry(),
					customer.getCust_level(),customer.getCust_address(),customer.getCust_phone());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	public void updateCustomer(Customer customer) {
		try {
			runner.update("update cst_customer set cust_name=?,cust_source=?,cust_industry=?,cust_level=?,cust_address=?,cust_phone=? where cust_id=?",
					customer.getCust_name(),customer.getCust_source(),customer.getCust_industry(),
					customer.getCust_level(),customer.getCust_address(),customer.getCust_phone(),customer.getCust_id());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void deleteCustomer(int custId) {
		try {
			runner.update("delete from cst_customer where cust_id=?",custId);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Customer findCustomerById(int custId) {
		try {
			return runner.query("select * from cst_customer where cust_id=?", new BeanHandler<Customer>(Customer.class),custId);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}

    建立CustomerService.java 實現業務層,將需要查詢的資料傳給Dao層,並得到Dao層的返回值。

package service;

import java.util.List;

import dao.ICustomerDao;
import dao.impl.CustomerDao;
import domain.Customer;

//客戶的業務層實現類
public class CustomerServiceImpl implements ICustomerService {

	private ICustomerDao customerDao=new CustomerDao();
	@Override
	public List<Customer> findAllCustomer() {
		// TODO Auto-generated method stub
		return customerDao.findAllCustomer();
	}

	@Override
	public void saveCustomer(Customer customer) {
		customerDao.saveCustomer(customer);

	}

	@Override
	public void updateCustomer(Customer customer) {
		customerDao.updateCustomer(customer);

	}

	@Override
	public void deleteCustomer(int custId) {
		customerDao.deleteCustomer(custId);
	}

	@Override
	public Customer findCustomerById(int custId) {
		// TODO Auto-generated method stub
		return customerDao.findCustomerById(custId);
	}

}

     五、測試類

           建立CustomerServiceTest.java 獲取CustomerServiceImpl所有方法的測試方法

            該類中在方法裡建立CustomerServiceImpl物件 獲取原始方法,將引數傳入Customer中,通過CustomerService獲取到返回值並列印。

package test;

import static org.junit.Assert.fail;

import java.util.List;

import org.junit.Test;

import domain.Customer;
import service.CustomerServiceImpl;
import service.ICustomerService;

public class CustomerServicerTest {

	@Test
	public void testFindAllCustomer() {
		ICustomerService cs=new CustomerServiceImpl();
		List<Customer> list=cs.findAllCustomer();
		for(Customer c: list){
			System.out.println(c);
		}
	}

	@Test
	public void testSaveCustomer() {
		ICustomerService cs=new CustomerServiceImpl();
		Customer c=new Customer();
		c.setCust_name("滴滴");
		c.setCust_source("dache");
		
		cs.saveCustomer(c);
	}

	@Test
	public void testUpdateCustomer() {
		fail("Not yet implemented");
	}

	@Test
	public void testDeleteCustomer() {
		fail("Not yet implemented");
	}

	@Test
	public void testFindCustomerById() {
		ICustomerService cs=new CustomerServiceImpl();
		Customer c=cs.findCustomerById(2);
		System.out.println(c);
	}

}

至此C3P0連線資料庫進行單表增刪改查功能完結。附上結構圖