我不確定你在問什麼,所以我做了兩種不同的方式...... 希望這會給你一個足夠好的例子來做任何你想做的事情。
----使用用戶對象----
的servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String fname = request.getParameter("firstName");
String lname = request.getParameter("lastName");
String dob = request.getParameter("dob");
String email = request.getParameter("email");
String uid = request.getParameter("userid");
dao.newUser(fname,lname,dob,email,uid);
}
userDAO的
public class UserDao {
private Connection connection;
public UserDao() {
connection = DbConnect.getConnection();
}
public void newUser(String fname, String lname, String dob, String email, String uid){
User user = new User();
user.setFirstName(fname);
user.setLastName(lname);
user.setDob(dob);
user.setEmail(email);
addUser(user);}
}
public void addUser(User user) {
try {
PreparedStatement preparedStatement = connection
.prepareStatement("insert into
users(firstname,lastname,dob,email) values (?, ?, ?, ?)");
preparedStatement.setString(1, user.getFirstName());
preparedStatement.setString(2, user.getLastName());
preparedStatement.setString(3, user.getDob());
preparedStatement.setString(4, user.getEmail());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
----無需用戶OBJECT ----
的servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String fname = request.getParameter("firstName");
String lname = request.getParameter("lastName");
String dob = request.getParameter("dob");
String email = request.getParameter("email");
String uid = request.getParameter("userid");
dao.addUser(fname,lname,dob,email,uid);
}
userDAO的
public class UserDao {
private Connection connection;
public UserDao() {
connection = DbConnect.getConnection();
}
public void addUser(String fname, String lname, String dob, String email, String uid) {
try {
PreparedStatement preparedStatement = connection
.prepareStatement("insert into users(firstname,lastname,dob,email) values (?, ?, ?, ?);");
preparedStatement.setString(1, fname);
preparedStatement.setString(2, lname);
preparedStatement.setString(3, dob);
preparedStatement.setString(4, email);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
將值傳遞給其他類作爲參數。 – BackSlash
向我們展示了所有涉及的代碼。 –
@ BackSlash ok,我會盡力去做* – Nurik