我正在尝试使用Java Servlet和mysql数据库创建注册页面。这是我的servlet代码的一部分。没有错误输出。数据库路径是100%正确
String uName = request.getParameter("username");
String pass = request.getParameter("passwd");
String rpass = request.getParameter("rpasswd");
String email = request.getParameter("email");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
final String DB_URL = "jdbc:mysql://127.0.0.1:3306/userData";
Connection con = DriverManager.getConnection(DB_URL, "serv", "serv");
String sql = "INSERT INTO users (username, password, em) values (?, ?, ?)";
PreparedStatement stat = con.prepareStatement(sql);
stat.setString(1, uName);
stat.setString(2, pass);
stat.setString(3,email);
con.close();
}
catch(SQLException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
}
答案 0 :(得分:2)
String uName = request.getParameter("username");
String pass = request.getParameter("passwd");
String rpass = request.getParameter("rpasswd");
String email = request.getParameter("email");
Class.forName("com.mysql.cj.jdbc.Driver");
final String DB_URL = "jdbc:mysql://127.0.0.1:3306/userData";
try (Connection con = DriverManager.getConnection(DB_URL, "serv", "serv")) {
final String sql = "INSERT INTO users (username, password, em) values (?, ?, ?)";
final PreparedStatement stat = con.prepareStatement(sql);
stat.setString(1, uName);
stat.setString(2, pass);
stat.setString(3, email);
stat.execute(); // you miss this
} catch(Exception e) {
System.out.println(e);
}
execute()
从PreparedStatement javadoc中执行此PreparedStatement对象中的SQL语句,该对象可以是任何类型的SQL语句。