如何匹配此Java servlet中数据库的Username和Pass。 JDBC和Servlet

问题描述 投票:1回答:1

我正在尝试将我的HTML登录页面与数据库连接。我编写了这个servlet但是在连接中遇到了一些错误。

        String name=request.getParameter("uname");//Passing the HTML tag to he string
        String psw= request.getParameter("psw");//
        String QUERY="SELECT *FROM login WHERE EMAIL=?,PASS=?"; //Query 




        Class.forName("com.mysql.jdbc.Driver");//Connection
        try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost/SmallERP", "root", "root")) {
            PreparedStatement ps = con.prepareStatement(QUERY);
            ps.setString(1, name);
            ps.setString(2, psw);
            try (ResultSet rs = ps.executeQuery()) {
                if(rs.next()){
                    out.println("Done");
                }else{
                    out.println("ERROR");
                }
            }
        }
java mysql jdbc prepared-statement
1个回答
1
投票

你必须在这里使用AND。修改后的查询:

String QUERY="SELECT * FROM login WHERE EMAIL=? And PASS=?";

我的完整示例是: -

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class GetUserDetailsUsingPS {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        // read user entered data
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter email id:");
        String id = scanner.nextLine();
        System.out.println("User id=" + id);
        System.out.println("Please enter password to get details:");
        String pwd = scanner.nextLine();
        System.out.println("User password=" + pwd);
        printUserData(id, pwd);
    }

    private static void printUserData(String id, String pwd) throws ClassNotFoundException,
            SQLException {

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String query = "select name, country, password from Users where email = ? and password = ?";
        try {
            con = DBConnection.getConnection();
            ps = con.prepareStatement(query);

            //set the parameter
            ps.setString(1, id);
            ps.setString(2, pwd);
            rs = ps.executeQuery();

            while (rs.next()) {
                System.out.println("Name=" + rs.getString("name") + ",country="
                        + rs.getString("country") + ",password="
                        + rs.getString("password"));
            }
        } finally {
            if (rs != null)
                rs.close();
            ps.close();
            con.close();
        }

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.