0

我有一个连接到 mySQL 数据库的肥皂网络服务。它有两种方法,一种是insert(),另一种是verify()。第一个允许用户输入数据,例如姓名、电子邮件和密码。它成功地将记录保存在数据库中。

但是在编写验证方法时遇到问题。它有作为输入参数,电子邮件和密码。它必须将输入的数据与存储在数据库中的数据进行比较,如果在 mysql 数据库中找不到匹配项,则返回“已注册”或“未注册”。编写代码时遇到问题。你能帮忙吗,我是 jdbc 和 java web 服务的新手。我正在使用netbeans。非常感谢。

这是我的代码:

    @WebMethod(operationName = "insert")
    public String insert(@WebParam(name = "name") String name,
    @WebParam(name = "email") String email,
    @WebParam(name = "password") String password {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con =          DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "1234");
        PreparedStatement st = con.prepareStatement("insert into register values(?,?,?)");
        st.setString(1, name);
        st.setString(2, email);
        st.setString(3, password);
        st.executeUpdate();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return "record inserted";
}

/**
 * Web service operation
 */
@WebMethod(operationName = "Verify")
public String CheckUser(@WebParam(name = "email") String email,  
@WebParam(name = "password") String password) {

        Class.forName("com.mysql.jdbc.Driver");
        Connection con =  DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "1234");

If
 // problems to write this statement!!! I need to compare the username and password 
// with some select * from register where password == @password and email == @email?

 return "Registered user";
 else 
    return "Not registered";

}
4

1 回答 1

0

此示例可能有效(您可能必须更改查询中的列名)。此外,您应该以与本示例相同的方式在插入方法中关闭连接。

    Connection con = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "1234");
        PreparedStatement st = con.prepareStatement("select 1 from register where password = ? and email = ? and name = ?");
        st.setString(1, password);
        st.setString(2, email);
        st.setString(3, name);

        ResultSet result = st.executeQuery();

        if (result.next()) { //.next() returns true if there is a next row returned by the query.
            return "Registered user";
        } else {
            return "Not registered";
        }


    } catch (Exception e) {
        //TODO manage the exception.
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {}
        }
    }
于 2012-10-30T17:04:41.340 回答