我有一个表单来获取用户输入,使用JSP和servlet以及两个java类来获取数据并将它们插入到数据库中。我使用mysql开发了数据库,它在tomcat服务器上运行。
表单中的数据通过post方法传递给servlet,并将它们存储在向量中。
这是servlet的代码:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String profession = request.getParameter("name");
String features = request.getParameter("address");
Vector<String> v = new Vector<String>();
v.addElement(name);
v.addElement(address);
Enumeration vEnum = v.elements();
j=SqlInsert.insertValues(vEnum);
if (j==0){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SubmitUser</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Error</h1>");
out.println("</body>");
out.println("</html>");
}
else{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SubmitUser</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Successfully Submmited</h1>");
out.println("</body>");
out.println("</html>");
}
这是java类(SqlInsert),它从vector获取元素并设置为sql:
public class SqlInsert{
static int i=0;
Connection c=null;
static PreparedStatement statement = null;
public static int insertValues(Enumeration<String> params) {
String sql = "INSERT INTO test (name, address
+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
try {
Connection c = DbConnection.connectDB();
System.out.println("connected " + c);
statement = c.prepareStatement(sql);
System.out.println("connected ");
c.setAutoCommit(false);
int k = 1;
while (params.hasMoreElements()) {
String param = params.nextElement();
statement.setString(k++, param);
}
i = statement.executeUpdate();
System.out.print(i);
c.commit();
} catch (SQLException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("e " + ex.toString());
}
return i;
}
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
Enumeration vEnum = v.elements();
SqlInsert.insertValues(vEnum);
}
}
这是建立数据库连接的java类
public class DbConnection {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/online_feedback";
private static Connection con;
public static Connection connectDB(){
try {
Class.forName(driver);
con = DriverManager.getConnection(url, "root", "");
System.out.println("Conn obj :::" + con);
} catch (ClassNotFoundException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(DbConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
public static void main (String []args){
DbConnection db = new DbConnection();
Connection s = db.connectDB();
}
我的问题是每当我提交表单时,似乎executeUpdate()返回0.在服务器日志中,没有显示任何内容
请帮助我完成它。任何帮助都将受到高度赞赏。
提前致谢