JDBCツールクラス抽出方式一(idクエリによるテスト)

1989 ワード

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);
		}
	}
}