JDBC访问数据库的方式——实例三

简介:

现在很多WEB服务器(Weblogic, WebSphere, Tomcat)都提供了DataSoruce的实现,即连接池的实现。通常我们把DataSource的实现,按其英文含义称之为数据源,数据源中都包含了数据库连接池的实现。
也有一些开源组织提供了数据源的独立实现:
DBCP 数据库连接池:

              DBCP 是 Apache 软件基金组织下的开源连接池实现,使用DBCP数据源,应用程序应在系统中增加如下两个 jar 文件
                         Commons-dbcp.jar:连接池的实现
                         Commons-pool.jar:连接池实现的依赖库

              Tomcat 的连接池正是采用该连接池来实现的。该数据库连接池既可以与应用服务器整合使用,也可由应用程序独立使用。
C3P0 数据库连接池:


实际应用时不需要编写连接数据库代码,直接从数据源获得数据库的连接。程序员编程时也应尽量使用这些数据源的实现,以提升程序的数据库访问性能。
注:lib中导入c3p0-0.9.2-pre1.jar

实例三(C3P0连接池):

1.在src目录下配置好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/bookstore</property>
		<property name="user">root</property>
		<property name="password">pass</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>

2.在JdbcUtil.java中获得DataSourse数据源及创建Connection对象

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JdbcUtils {

	private static DataSource ds = null;
	static{
		ds = new ComboPooledDataSource();
	}
	
	public static DataSource getDataSource(){
		return ds;
	}
	
	public static Connection getConnection() throws SQLException{
		return ds.getConnection();
	}
}

3.数据访问层中的增删改查写法:

public class BooksDaoImpl implements BooksDao {
	@Override
	public void addBook(Books book) {
		try{
		QueryRunner qr=new QueryRunner(JdbcUtil_dbcp.getDataSource());
		String sql="insert into books(id,name,price,author,description,images,category_id) values(?,?,?,?,?,?,?)";
		Object params[]={book.getId(),book.getName(),book.getPrice(),book.getAuthor(),book.getDescription(),book.getImages(),book.getCategory().getId()};
		qr.update(sql, params);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	@Override
	public void deleteBook(String id) throws IdNullException {
		Connection conn=null;
		try{
			if(id==null || id.equals("")){
				throw new IdNullException("id不能为空");
			}
			QueryRunner qr=new QueryRunner();
			conn=JdbcUtil_dbcp.getConnection();
			conn.setAutoCommit(false);
			String sql="delete from orderitem where book_id=?";
			qr.update(conn,sql, id);
			sql="delete from books where id=?";
			qr.update(conn, sql, id);			
			conn.commit();
		}catch(Exception e){
			try {
				conn.rollback();
				conn.commit();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			throw new RuntimeException(e);
		}finally{
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void updateBook(Books book) throws IdNullException {
		try{
			if(book.getId()==null || book.getId().equals("")){
				throw new IdNullException("id不能为空");
			}
			QueryRunner qr=new QueryRunner(JdbcUtil_dbcp.getDataSource());
			String sql="update books set name=?,price=?,author=?,description=?,images=?,category_id=? where id=?";
			Object params[]={book.getName(),book.getPrice(),book.getAuthor(),book.getDescription(),book.getImages(),book.getCategory().getId(),book.getId()};
			qr.update(sql, params);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	@Override
	public List<Books> findAll() {
		try{
			QueryRunner qr=new QueryRunner(JdbcUtil_dbcp.getDataSource());
			String sql="select * from books";
			return qr.query(sql, new BeanListHandler<Books>(Books.class));
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	@Override
	public Books findById(String id) throws IdNullException {
		try{
			QueryRunner qr=new QueryRunner(JdbcUtil_dbcp.getDataSource());
			String sql="select * from books where id=?";
			return qr.query(sql, new BeanHandler<Books>(Books.class),id);
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}




 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
JDBC访问数据库的步骤 1. 新建java项目:JDBC,新建 class文件:TestJDBC 2. JDBC用到的类库基本都位于java.sql.*包中,程序中引入该包: Import java.sql.*; 3. 添加要用的数据库中的包,找到数据库中的Driver.class文件: 项目名上点右键,Build Path—Add External Archives… 构建路径----添加外部归档 加入mysql-connector-java-5.1.12 4. 从包中找到要用的驱动,展开包,从中找到Driver.class,编程时,先把这个类的驱动new一个实例对象出来,告诉DriverManage,要连到哪种数据库上: 方法一:Class.forName(“com.mysql.jdbc.Driver”); Class: java.lang中的特殊类,类的装载器; forName: 会抛异常; com.mysql.jdbc.Driver中的Driver会new一个它的实例对象 方法二:new com.mysql.jdbc.Driver(); new出来后会自动向DriverManage注册。 5. 得到数据库的连接: Connection conn=DriverManager.getConnection (数据库的连接串,用户名,密码); 数据库的连接串:“jdbc:mysql://localhost:3306/books” 用户名: “root” 密码: “111” 程序调试: import java.sql.*; public class TestJDBC { public static void main(String[] args)throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection conn=DriverManager.getConnection ("jdbc:mysql://localhost:3306/books?","root","111"); System.out.println("Connection Successful!"); } } * *对数据库表的操作通常有:executeQuery() executeUpdate() 6. (1)应用Statement接口 获取Statement对象,通过Statement对象执行SQL语句: Statement stmt=con.createStatement(); 执行SQL查询,返回给结果集对象: ResultSet rs=stmt. executeQuery(“select * from 表名”); 或 表名”+条件); 遍历访问数据表:while(rs.next()) 以各种类型显示输出:rs.get×××(“字段名”) (2)应用PreparedStatement接口 (p203) 执行数据更新executeUpdate():insert、update、delete SQL语句的创建:String sql=“sql命令”; 创建PreparedStatement的对象: pstmt=con. PrepareStatement(sql); 执行赋值操作(“?”占位符的用法): 执行:insert、update、delete result=pstmt. executeUpdate(); result类型为整型,返回一个整数,小于零操作没成功 7.关闭不再使用的 如:rs.close(); stmt.close(); con.close(); JDBC编程步骤总结: 1. Load the Driver:Class.forName(); 2. Connect the DateBase: DriveManager.getConnection() 3. Execute the SQL: (1) Connection.createStatement() Connection.prepareStatement(sql) (2)Statement.executeQuery() (3)Statement.executeUpdate() 4. Retrieve the result data: 循环取得结果while(rs.next()) 5. Show the result data:将遍历的结果记录显示出来 6.Close:结束时关闭 //完善的JDBC程序 import java.sql.*; public class TestJDBC { public static void main(String[] args) { Connection conn=null; Statement stmt=null; ResultSet rs=null; try{ Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/books?","root","111"); System.out.println("Connection Successful!"); stmt=conn.createStatement(); rs=stmt.executeQuery("select * from titles"); while (rs.next()){ System.out.println(rs.getString("isbn")+" "+rs.getString("title")); } }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); }finally{ try{ if(rs!=null){ rs.close(); rs=null; } if(stmt!=null){ stmt.close(); stmt=null; } if(con!=null){ con.close(); con=null; } }catch(SQLException e){ e.printStackTrace(); } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

招风的黑耳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值