这段代码哪里出错了!这是一段留言板提交留言到数据库的代码,可是实验显示不能正确提交到数据库!求解!代码主体:
<% String sql;String name=request.getParameter("name");if(name==null) {name=""; }String mail=request.getParameter("mail");if(mail==null) {mail=""; }String title=request.getParameter("title"); if(title==null) {title=""; }String content=request.getParameter("content"); if(content==null) {content=""; }if(name.length()==0) out.println("留言人的姓名不能为空!"); else if(title.length()==0) out.println("留言主题不能为空!"); else if(content.length()==0) out.println("留言内容不能为空!"); else { Class.forName("com.mysql.jdbc.Driver").newInstance(); String url="jdbc:mysql://localhost:3306/mydb"; Connection con=DriverManager.getConnection(url,"root","admin"); Statement stm=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);try { sql="Insert Into user(name,mail,title,content) Values('"+name+"','"+mail+"','"+title+"',"+content+")";stm.executeQuery(sql); } catch(Exception e) { out.println(e.getMessage());} ResultSet rs=stm.executeQuery("select * from user");rs.close();con.close(); %> <% } %>1条回答 默认 最新
- ChatGPTᴼᴾᴱᴺᴬᴵ 2023-12-09 19:14关注
所有内容均由人工智能模型输出,其内容的准确性和完整性无法保证,不代表我的态度或观点。
(讯飞星火专栏,V3.0版本,2023.10.24)
该回答引用讯飞星火认知大模型,仅提供参考,不保证完全正确
这段代码中存在一些问题,我将为您指出并提供修改后的代码。在插入数据时,您使用了
executeQuery()
方法,但实际上应该使用executeUpdate()
方法。因为您要插入的是一条记录,而不是查询结果。在拼接SQL语句时,您没有对字符串进行转义,这可能导致SQL注入攻击。建议使用
PreparedStatement
来避免这个问题。在输出错误信息时,建议使用
out.println()
方法,而不是直接使用out.print()
。这样可以确保错误信息被正确输出。
修改后的代码如下:
<% String sql; String name=request.getParameter("name"); if(name==null) { name=""; } String mail=request.getParameter("mail"); if(mail==null) { mail=""; } String title=request.getParameter("title"); if(title==null) { title=""; } String content=request.getParameter("content"); if(content==null) { content=""; } if(name.length()==0) { out.println("留言人的姓名不能为空!"); } else if(title.length()==0) { out.println("留言主题不能为空!"); } else if(content.length()==0) { out.println("留言内容不能为空!"); } else { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); String url="jdbc:mysql://localhost:3306/mydb"; Connection con=DriverManager.getConnection(url,"root","admin"); PreparedStatement pstmt = con.prepareStatement("Insert Into user(name,mail,title,content) Values(?,?,?,?)"); pstmt.setString(1, name); pstmt.setString(2, mail); pstmt.setString(3, title); pstmt.setString(4, content); pstmt.executeUpdate(); ResultSet rs=pstmt.executeQuery("select * from user"); rs.close(); con.close(); } catch(Exception e) { out.println(e.getMessage()); } } %>
请注意,这段代码仍然存在一些潜在的问题,例如数据库连接的关闭顺序和异常处理。在实际项目中,您可能需要根据具体需求进行调整。
解决 无用评论 打赏 举报
悬赏问题
- ¥15 如何在scanpy上做差异基因和通路富集?
- ¥20 关于#硬件工程#的问题,请各位专家解答!
- ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
- ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
- ¥30 截图中的mathematics程序转换成matlab
- ¥15 动力学代码报错,维度不匹配
- ¥15 Power query添加列问题
- ¥50 Kubernetes&Fission&Eleasticsearch
- ¥15 報錯:Person is not mapped,如何解決?
- ¥15 c++头文件不能识别CDialog