JDBC工具类抽取方式一(测试根据id查询)

package cn.itheima.jdbc;
/**
 * 提供获取连接和释放资源的方法
 * @author XING
 *
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCUtils_V1 {
	/**
	 * 获取连接方法
	 * 
	 * @return
	 */
	public static Connection getConnection(){
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web08", "root", "root");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs){
		if (rs !=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (pstmt !=null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn !=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
package cn.itheima.jdbc.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

import cn.itheima.jdbc.JDBCUtils_V1;

/**
 * 测试工具类
 * 
 * @author XING
 *
 */
public class TestUtils {

	/**
	 * 根据id查询用户信息
	 */
	@Test
	public void testFindUserById(){
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			//1.获取连接
			 conn = JDBCUtils_V1.getConnection();
			//2.编写SQL语句
			String sql = "select * from tbl_user where uid=?";
			//3.获取执行SQL语句对象
			pstmt = conn.prepareStatement(sql);
			//4.设置参数
			pstmt.setInt(1, 2);
			//5.执行查询操作
			rs = pstmt.executeQuery();
			//6.处理结果集
			while(rs.next()){
				System.out.println(rs.getString(2)+"----"+rs.getString("upassword"));
			}
			//释放资源能放在此处行么?【不行滴!】
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//7.释放资源
			JDBCUtils_V1.release(conn, pstmt, rs);
		}
	}
}

 

 

 

你可能感兴趣的:(JAVA笔记)