我有成功建立与mySQL数据库的连接的代码。
String email, password; //assume these are already loaded with user-entered data.
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
return false;
}
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/main", "root", "password123");
} catch (SQLException e) {
return false;
}
//perform my database actions here///////////////
///////////////////////////////////////////////////
try {
conn.close();
} catch (SQLException e) {
return false;
}
我在上面的代码范围内有几个字符串,已经有一个用户在登录页面上输入的电子邮件和密码。我需要在数据库中查找匹配的电子邮件地址,然后验证密码是否与用户在表单中输入的密码匹配。
我的表有3列:ID,电子邮件和密码。
我已经使用sql工作台将两行推入表中
1 | email@gmail.com |密码1
2 | email2@gmail.com |密码2
我假设在纯SQL中,我必须做类似的事情
SELECT * FROM users WHERE email LIKE 'email@gmail.com' AND password LIKE 'password1';
但是我不太确定如何使用JSP将这些SQL命令实际发送到数据库并接收信息。另外,我也不完全确定我的SQL逻辑是验证密码的理想方法。我对上面的SQL命令的想法是,如果数据库找到符合条件的任何行,则将验证电子邮件/密码组合。不确定这是否是一种很好的方法。我并不是在寻找最安全,最复杂的方法,而是在寻找目前最有意义的最简单方法。我发现的每个教程似乎都有不同的用法,我有些困惑。
最佳答案
这是一个示例,您可以从我从事的工作中使用(假设连接“ conn”很明显):
PreparedStatement st = null;
ResultSet rec = null;
SprayJobItem item = null;
try {
st = conn.prepareStatement("select * from sprayjob where headerref=? and jobname=?");
st.setString(1, request.getParameter("joblistref"));
st.setString(2, request.getParameter("jobname"));
rec = st.executeQuery();
if (rec.next()) {
item = new SprayJobItem(rec);
}
} catch (SQLException ex) {
// handle any errors
ReportError.errorReport("SQLException: " + ex.getMessage());
ReportError.errorReport("SQLState: " + ex.getSQLState());
ReportError.errorReport("VendorError: " + ex.getErrorCode());
} catch (Exception ex) {
ReportError.errorReport("Error: " + ex.getMessage());
} finally {
// Always make sure result sets and statements are closed,
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
;
}
ps = null;
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
;
}
rs = null;
}
}
就您而言,而不是
item = new SprayJobItem(rec);
您将拥有指出该用户有效的代码,因为已找到该记录。