这段代码哪里出错了!这是一段留言板提交留言到数据库的代码,可是实验显示不能正确提交到数据库!求解!代码主体:
<% 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 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
- ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
- ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
- ¥15 乘性高斯噪声在深度学习网络中的应用
- ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
- ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
- ¥15 C++ 头文件/宏冲突问题解决
- ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
- ¥50 安卓adb backup备份子用户应用数据失败
- ¥20 有人能用聚类分析帮我分析一下文本内容嘛