java-JDBC登陸註冊代碼

登陸:html

public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        System.out.println("帳號:");
        String uid = sc.nextLine();
        System.out.println("密碼:");
        String pwd = sc.nextLine();
        
        Class.forName("com.mysql.jdbc.Driver");
        
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","");
        String sql = "select * from users where user = ? and password = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, uid);
        ps.setString(2, pwd);
        ResultSet rs = ps.executeQuery();
        boolean ok = rs.next();
        if(ok){
            System.out.println("歡迎"+rs.getString(3)+"回來");
        }
        else
        {
            System.out.println("您輸入的帳號密碼有誤");
        }
        }

這是一個簡單的經過輸入數據跟數據庫的數據比較來完成登陸驗證。這裏用的是PreparedStatementmysql

PreparedStatement 與Statement 的區別

1  有安全性sql

    PreparedStatement 能夠因爲不是使用拼接,防止了sql注入,提升了安全性。數據庫

2  更方便安全

    PreparedStatement 能夠自動對類型進行轉換,代碼可讀性,可維護性提升。post

 

3  批處理ui

   PreparedStatement 有預編譯功能,大批量的處理sql效率更高。(MySQL 不明顯,Oracle 很是明顯)url

 

註冊:spa

public static void main (String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入帳號");
        String uid = sc.nextLine();
        System.out.println("請輸入密碼");
        String pwd = sc.nextLine();
        System.out.println("請輸入暱稱");
        String nc = sc.nextLine();
        
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?characterEncoding=GBK","root","");
        String sql =  "insert into users values (?,?,?)";
        
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, uid);
        ps.setString(2, pwd);
        ps.setString(3, nc);
        ps.executeUpdate();
        conn.close();
        
        
        
    }
相關文章
相關標籤/搜索