06PreparedStatement類詳解

package cn.itcast.jdbc;java

import cn.itcast.util.JDBCUtils;sql

import java.sql.*;
import java.util.Scanner;數據庫

/**code

  • 練習:
    • 需求:
    1. 經過鍵盤錄入用戶名和密碼
    1. 判斷用戶是否登陸成功

*/
public class JDBCDemo9 {對象

public static void main(String[] args) {
    //1.鍵盤錄入,接受用戶名和密碼
    Scanner sc = new Scanner(System.in);
    System.out.println("請輸入用戶名:");
    String username = sc.nextLine();
    System.out.println("請輸入密碼:");
    String password = sc.nextLine();
    //2.調用方法
    boolean flag = new JDBCDemo9().login2(username, password);
    //3.判斷結果,輸出不一樣語句
    if(flag){
        //登陸成功
        System.out.println("登陸成功!");
    }else{
        System.out.println("用戶名或密碼錯誤!");
    }


}



/**
 * 登陸方法
 */
public boolean login(String username ,String password){
    if(username == null || password == null){
        return false;
    }
    //鏈接數據庫判斷是否登陸成功
    Connection conn = null;
    Statement stmt =  null;
    ResultSet rs = null;
    //1.獲取鏈接
    try {
        conn =  JDBCUtils.getConnection();
        //2.定義sql
        String sql = "select * from user where username = '"+username+"' and password = '"+password+"' ";
        System.out.println(sql);
        //3.獲取執行sql的對象
        stmt = conn.createStatement();
        //4.執行查詢
        rs = stmt.executeQuery(sql);
        //5.判斷
       /* if(rs.next()){//若是有下一行,則返回true
            return true;
        }else{
            return false;
        }*/
       return rs.next();//若是有下一行,則返回true

    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        JDBCUtils.close(rs,stmt,conn);
    }


    return false;
}

/**
 * 登陸方法,使用PreparedStatement實現
 */
public boolean login2(String username ,String password){
    if(username == null || password == null){
        return false;
    }
    //鏈接數據庫判斷是否登陸成功
    Connection conn = null;
    PreparedStatement pstmt =  null;
    ResultSet rs = null;
    //1.獲取鏈接
    try {
        conn =  JDBCUtils.getConnection();
        //2.定義sql
        String sql = "select * from user where username = ? and password = ?";
        //3.獲取執行sql的對象
        pstmt = conn.prepareStatement(sql);
        //給?賦值
        pstmt.setString(1,username);
        pstmt.setString(2,password);
        //4.執行查詢,不須要傳遞sql
        rs = pstmt.executeQuery();
        //5.判斷
       /* if(rs.next()){//若是有下一行,則返回true
            return true;
        }else{
            return false;
        }*/
        return rs.next();//若是有下一行,則返回true

    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        JDBCUtils.close(rs,pstmt,conn);
    }


    return false;
}

}get

相關文章
相關標籤/搜索