请问怎么在servlet里面写数据库insert代码? 
这个是我写的~访问不到数据库希望大家帮我改下~~万分感谢!public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name").trim();
String password = request.getParameter("password").trim();
String sql = "insert into userdata(name,password)values('"+name+"','"+password+"')";
Connection con = null;
try {
con = new ConnectDB().getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);

if (rs.next()) {
out.write("Success");
//System.out.println("h");


out.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

解决方案 »

  1.   


    try   { 
    con   =   new   ConnectDB().getConnection(); 
    Statement   stmt   =   con.createStatement(); 
    ResultSet   rs   =   stmt.executeQuery(sql); if   (rs.next())   { 
    out.write( "Success "); 
    //System.out.println( "h "); 
    }   改成try   { 
    con   =   new   ConnectDB().getConnection(); 
    Statement   stmt   =   con.createStatement(); 
    stmt.executeQuery(sql) if   (stmt.executeUpdate(sql) > 0){ 
    out.write( "Success "); 
    //System.out.println( "h "); 
    }  
     
      

  2.   

    这样不是更好吗?
    try   { 
    con   =   new   ConnectDB().getConnection(); 
    Statement   stmt   =   con.createStatement(); 
    int n=stmt.executeUpdate(sql) ;//n是影响的行数
    if   (n > 0){ 
    out.write( "Success "); 
    }  
      

  3.   

    建议另建类进行数据库存储,通过servlet调用。
    存取方法可以参考楼上朋友的
      

  4.   

    还有楼主没告诉我们是什么数据库
    不同数据库连接字不同,还有驱动jar包是否有。
      

  5.   

    你执行的是INSERT,不是select,所以没有结果集
    http://www.10zhizui.cn
      

  6.   

    楼主,建议你另外创建一个dao类专门执行和数据库有关的操作,我觉得从mvc角度应该这样吧.
    servlet不该去做这些的.
      

  7.   

    数据库→DAO层→业务层→Servlet层→页面层,这样子的调用会比较好一些。