authenticate via MySQL User name table - Java java.sql

Java examples for java.sql:MySQL

Description

authenticate via MySQL User name table

Demo Code


//package com.java2s;
import java.sql.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        String username = "java2s.com";
        String password = "java2s.com";
        System.out.println(authenticate(username, password));
    }/*from  w w w  .j  ava2  s.  c  o m*/

    public static boolean authenticate(String username, String password) {
        ResultSet rs = null;
        PreparedStatement ps = null;
        Connection con = null;
        boolean status = false;

        try {

            //loading drivers for mysql
            Class.forName("com.mysql.jdbc.Driver");

            //creating connection with the database 
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/cs3520", "root", "simi");
            ps = con.prepareStatement("select * from User where username=? and password=?");
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();
            status = rs.next();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                ps.close();
                con.close();
            } catch (Exception e) {

            }
        }
        /*
        //implement credential check
        if(username.equals("simi") || username.equals("admin") || username.equals("Singh")){
        status = true;
        }
         */
        return status;

    }
}

Related Tutorials