JDBC

1.使用JDBC API 访问数据库的基本步骤

1)加载JDBC驱动程序

    

Class.forName("com.mysql.jdbc.Driver");

  

2)建立数据库连接

//利用DriverManager类的方法getConnection()获得与特定数据库的连接实例
 String url="jdbc:mysql://127.0.0.1:3306/library?useUnicode=true&characterEncoding=utf-8";
    	 String user="root";
    	 String password="";
    	 Connection conn=(Connection) DriverManager.getConnection(url, user, password);

  

3)创建操作数据库SQL的Statement,或者是PreparedStatement或CallableStatemen

//1.利用Statement对象执行“静态”SQL语句
//步骤一:创建Statement对象,其中conn为Connection对象
Statement statement=conn.createStatement();
//步骤二:使用executeQuery()方法执行Select语句,该方法的返回值为ResultSet类型
//注意,这边返回的ResultSet都是针对于查询语句的,而删除语句等等都不是使用executeQuery(),而是使用executeUpdate()方法,且是返回一个数字,如果大于0,成功,否失败。这边我们都使用查询语句
ResultSet rs=statement.executeQuerry("select * from table");


//2.利用PrepareStatement执行动态SQL语句
  PreparedStatement pstmt=null;
  String sql="SELECT * FROM goods_info where id like ?";
   pstmt=(PreparedStatement)conn.prepareStatement(sql);
   //这里面的数字对应你的?,如果这里面有两个?,那么我们就可以动态设值两个值
   pstmt.setString(1, "%"+idmohu+"%");
 ResultSet rs=pstmt.executeQuery();


//3.利用CallableStatement执行存储过程
//步骤一:首先先要在navicat等工具中创建一个过程,这边的过程名sp_SearchUser

//在java代码中如何书写:
CallableSatement cs=con.prepareCall("{call sp_SearchUser}");
//使用setXxx方法为IN参数赋值,此处IN参数为String类型,故使用setString()
cs.setString(1,"Allen");
//执行存储过程,该存储过程为执行一个查询,故使用executeQuery()方法
ResultSet rs=cs.executeQuery();

  

4)执行语句并分析执行结果

核心:如果是查询的话,用executeQuery()方法,其返回一个ResultSet,我们对该集合进行遍历,取出数据。如果是添加或者是删除等,使用executeUpdate()方法,其返回的一般是int值,如果大于0就操作成功,否则,失败。

 

5)关闭连接

 核心:关闭顺序

1.先关闭结果集ResultSet

2.再关闭Statement等对象

3.关闭连接对象

 

 

2.设置数据库公共池访问类

import java.sql.DriverManager;
import java.sql.ResultSet;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import com.sun.crypto.provider.RC2Cipher;

//注意:这边的方法和参数都是使用静态的,因为方便调用
public class DbUtil {
     /*
      * 声明连接数据库的信息,例如数据库URL,用户名和密码
      */
	private static final String URL="jdbc:mysql://localhost:3306/userdb";
	private static final String USER="root";
	private static final String PASSWORD="";
	
	/*
	 * 声明JDBC的相关对象
	 */
	protected static Statement s=null;
	protected static ResultSet rs=null;
	protected static Connection connection=null;
	
	/*
	 * 创建数据库连接,注意要加上锁
	 */
	public static synchronized Connection getConnection()
	{
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection=(Connection) DriverManager.getConnection(URL,USER,PASSWORD);	
		}catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
	
	/*
	 * 执行Insert,update,delete语句
	 */
	public static int executeUpdate(String sql) {
		int result=0;
		try {
	       s=(Statement) getConnection().createStatement();
	       result=s.executeUpdate(sql);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/*
	 * 执行select语句
	 */
	public static ResultSet executeQuery(String sql) {
		try {
			 s=(Statement) getConnection().createStatement();
			 rs=s.executeQuery(sql);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	/*
	 * 执行动态SQL语句
	 */
	public static PreparedStatement executePrepareStatement(String sql)
	{
		PreparedStatement ps=null;
		try {
			ps=(PreparedStatement) getConnection().prepareStatement(sql);
			
		}catch (Exception e) {
		    e.printStackTrace();
		}
		return ps;
	}
	
	/*
	 * 事务回滚
	 */
	public static void rollback() {
		try {
			getConnection().rollback();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 关闭数据库连接对象
	 */
	public static void close() {
		try {
			if(rs!=null)
				rs.close();
			if(s!=null) 
				s.close();
			if(connection!=null) {
				connection.close();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}

  

     3.数据库连接池

1)数据库连接池简介

    数据库连接池就是一个虚拟的池中预先创建好一定数量的Connection对象等待客户端连接数据库,当这个客户端请求结束时则将Connection对象归还给池中,用来等待下一个客户端的访问。其工作过程如下:

(1)预先定义一定数量的连接,并存放在数据库连接池中。

(2)当客户端请求一个连接数据库时,系统将从数据库连接池中为其分配一个空闲的连接,而不是重新建立一个连接对象;当该请求结束后,该连接会归还到数据库连接池中,而不是直接将其释放。

(3)当连接池中的空闲连接数量低于下限时,连接池将会根据配置信息追加一定数量的连接对象,当空闲连接数量高于上限时,连接池会释放一定数量的连接。

注意:在使用数据库连接池时,如果连接对象不在继续使用时,需要及时地调用连接对象的close()方法将该连接对象作为空闲连接"归还"给连接池,以便让其他数据库连接请求使用。

 

2)数据库连接池技术优势

(1)创建一个新的数据库连接所耗费的时间主要取决于网络的速度以及应用程序和数据库服务器的距离,而且这个过程通常是一个很耗时间的过程,采用数据库连接池后,数据库连接请求则可以直接通过连接池满足,不需要为该请求重新连接,认证到数据库服务器,从而节省时间。

(2)提高了数据库连接的重复使用率。

(3)解决了数据库对连接数量的限制。

 

3)数据库连接池技术的实现

方式一:基于web服务器的数据库连接池

第一步:在web应用的META-INF下新建context.xml文件,配置数据源。

<?xml version="1.0" encoding="UTF-8”?>
<Context>
   <Resource name="dbpool"
    type="javax.sql.DataSource"
    auth="Container"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/test"
    username="root"
    password="123"
    maxActive="5"
    maxIdle="2"
    maxWait="6000" />
</Context>

第二步:使用JNDI访问数据库连接池(在数据库操作工具中修改)

/*
	 * 创建数据库连接,注意要加上锁,这边改成了用连接池来操作数据库
	 */
	public static synchronized Connection getConnection()
	{
		try {
			//Context时javax.name包中的一个接口,用于查找数据库连接池的配置文件
			Context ctx=new InitialContext();
			ctx=(Context)ctx.lookup("java:comp/env");
			/*dbpool为context.xml文件中Resource元素的name属性值*/
			DataSource ds=(DataSource) ctx.lookup("dbpool");
			connection=(Connection) ds.getConnection();
		}catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("完成连接");
		return connection;
	}

  

 

posted @ 2017-11-08 15:47  鹏达君  阅读(180)  评论(0编辑  收藏  举报