如何匹配这个javaservlet中的用户名并从数据库中传递jdbc和servlet

x7yiwoj4  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(276)

我正在尝试连接我的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");
                }
            }
        }
thtygnil

thtygnil1#

你必须使用 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();
        }

    }
}

相关问题