JSP进行数据库操作无法实现插入操作
<%@pagelanguage="java"import="java.sql.*"errorPage=""%><jsp:useBeanid="conn"scope="pa...
<%@ page language="java" import="java.sql.*" errorPage=""%>
<jsp:useBean id = "conn" scope = "page" class = "com.DB.connDB" />
<%
int sum = 0;
if(request.getParameter("sum") == null){sum = 1;}
else{sum = Integer.parseInt(request.getParameter("sum"));}
for(int i=1; i <= sum; i++){
String uname = new String(request.getParameter("uName_"+i).getBytes("ISO8859-1"),"gb2312");
String uid = request.getParameter("uId_"+i);
int kind = Integer.parseInt(request.getParameter("kind_"+i));
if(uname == "" || uid == ""){continue;}
else{
String sql = "insert into db_User (uName, uId, kind) values ('" +uname+ "','" +uid+ "'," +kind+ ")";
//out.print(sql+"*****");
try{
int rs = conn.executeUpdate(sql);
//out.print(rs);
conn.close();
}catch(Exception e){
e.printStackTrace();
out.print("<script language='javascript'>alert('存入数据库失败!');</script>");
}
}
}
out.print("有"+sum+"条记录存入数据库!");
%>
其中,uname、uid和kind,都是从上一页面获得的数据,我已经通过out.print()语句输出sql和rs(即conn.executeUpdate),显示sql输出正常,rs为0,即未成功存入数据库。
我也通过
<% ResultSet test = conn.executeQuery("select ID from db_User");
while(test.next()){
String id = test.getString("ID");
out.print(id+"++");
}
%>验证了conn是可用的,能够得到正确的结果。
在整个运行过程中,未显示出错,也未抛出异常。 展开
<jsp:useBean id = "conn" scope = "page" class = "com.DB.connDB" />
<%
int sum = 0;
if(request.getParameter("sum") == null){sum = 1;}
else{sum = Integer.parseInt(request.getParameter("sum"));}
for(int i=1; i <= sum; i++){
String uname = new String(request.getParameter("uName_"+i).getBytes("ISO8859-1"),"gb2312");
String uid = request.getParameter("uId_"+i);
int kind = Integer.parseInt(request.getParameter("kind_"+i));
if(uname == "" || uid == ""){continue;}
else{
String sql = "insert into db_User (uName, uId, kind) values ('" +uname+ "','" +uid+ "'," +kind+ ")";
//out.print(sql+"*****");
try{
int rs = conn.executeUpdate(sql);
//out.print(rs);
conn.close();
}catch(Exception e){
e.printStackTrace();
out.print("<script language='javascript'>alert('存入数据库失败!');</script>");
}
}
}
out.print("有"+sum+"条记录存入数据库!");
%>
其中,uname、uid和kind,都是从上一页面获得的数据,我已经通过out.print()语句输出sql和rs(即conn.executeUpdate),显示sql输出正常,rs为0,即未成功存入数据库。
我也通过
<% ResultSet test = conn.executeQuery("select ID from db_User");
while(test.next()){
String id = test.getString("ID");
out.print(id+"++");
}
%>验证了conn是可用的,能够得到正确的结果。
在整个运行过程中,未显示出错,也未抛出异常。 展开
2个回答
展开全部
以下是修改后的代码,多了第三行代码,仔细看下
try{
int rs = conn.executeUpdate(sql);
conn.commit(); //提交事务,不执行该操作,数据还未保存到数据库
//out.print(rs);
conn.close();
}catch(Exception e){
e.printStackTrace();
out.print("<script language='javascript'>alert('存入数据库失败!');</script>");
}
try{
int rs = conn.executeUpdate(sql);
conn.commit(); //提交事务,不执行该操作,数据还未保存到数据库
//out.print(rs);
conn.close();
}catch(Exception e){
e.printStackTrace();
out.print("<script language='javascript'>alert('存入数据库失败!');</script>");
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询