我要从reg表单中读取数据并将其插入数据库,这部分应该添加项目但不起作用。你有推荐吗?
if ("/RegForm".equals(url)) {
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;
} else if ("/Signup".equals(url)) {
//dddddddd
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/deneme", "root", "");
Statement stmt = conn.createStatement();
// Execute SQL query
String sql1 = "INSERT INTO students (name, id, `gpa`) VALUES ("+ request.getParameter("st_name") +","+ request.getParameter("st_id") +","+ request.getParameter("st_gpa") +")";
stmt.executeUpdate(sql1);
} catch (Exception se) {
//Handle errors for JDBC
}
request.getRequestDispatcher("/register_action.jsp").forward(request, response);
return;
}
ps:我真的不熟悉在网络应用中使用java,只是想学习。
答案 0 :(得分:0)
你得到的任何具体错误..? 或者做一件事就像这样打印计数:
int count= stmt.executeUpdate(sql1);
检查计数值。把一些S.O.P放在其他条件中并交叉检查它是否会转到该部分。
答案 1 :(得分:0)
您应该使用preparedStatement来避免sql injection,您的代码应该是:
if ("/RegForm".equals(url)) {
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;
} else if ("/Signup".equals(url)) {
//dddddddd
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/deneme", "root", "");
PreparedStatement preparedStatement = null;
// Execute SQL query
String insert= "INSERT INTO students (name, id, `gpa`) VALUES (?,?,?)";
conn.setAutoCommit(false);
preparedStatement = con.prepareStatement(insert);
//Assume all paramaters as String
preparedStatement.setString(1, request.getParameter("st_name"));
preparedStatement.setString(2, request.getParameter("st_id"));
preparedStatement.setString(3, request.getParameter("st_gpa"));
preparedStatement.executeUpdate();
conn.commit();
} catch (Exception se) {
//Handle errors for JDBC
}
request.getRequestDispatcher("/register_action.jsp").forward(request, response);
return;
}
您可以在此处查看更多detailed example