package web09; /*获取连接和释放资源的方法 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class jdbc_text1 { 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) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } public static void release(Connection conn,PreparedStatement pstmt ,ResultSet rs){ //获取连接,创建预处理对象,执行查询操作 if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(pstmt!=null){ try { pstmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
package web09; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.junit.Test; /** * 测试工具类 * @author Administrator * */ public class jdbc_text2 { @Test public void textfinduserbyid(){ Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try { //1.获取链接 conn = jdbc_text1.getconnection(); //2编写sql语句 String sql ="select * from tbl_user where uid=?"; //3获取执行sql语句对象 pstmt = conn.prepareStatement(sql); //4设置参数 pstmt.setInt(1, 2); //setint(第一个表示第一个获取位置,第二个表示值) //5设置查询操作 rs =pstmt.executeQuery(); while(rs.next()){ System.out.println(rs.getString(2)+"------------"+rs.getString("upassword")); } } catch (SQLException e) { e.printStackTrace(); }finally { jdbc_text1.release(conn, pstmt, rs); } } }