日期:2014-05-19  浏览次数:20906 次

求救:代码看不懂
不懂运行结果为什么是mid = 0的?以下是部分代码:

public int testInsert(String sql){
Connection conn = null;
PreparedStatement st = null;
int mid = -1;
try{
conn = getConnection();
String [] c = {"bno"};
st = conn.prepareStatement(sql,c);
st.execute();
ResultSet rs = st.getGeneratedKeys();
if(rs.next())
mid = rs.getInt(1);
System.out.println(mid);
rs.close();

}catch(SQLException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if (st!=null)
st.close();
if (conn !=null)
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
return mid;
}

public static void main(String[] args){
JdbcTest j = new JdbcTest();
j.testInsert("Insert into bookinf values('1113','acb','dd','80','10','10')");
j.testQuery("%%");
}



运行结果如下:
0
id:1101bookname:acbwriter:ddpno:80
id:1102bookname:大学日语writer:沫沫pno:120
id:1103bookname:JAVA2writer:陈亮pno:130
id:1104bookname:管理学writer:林立pno:140
id:1105bookname:经济学writer:比比pno:150
id:1106bookname:基础理论writer:偲偲pno:160
id:1107bookname:dfdfrtwrtrwriter:gfertrpno:162
id:1108bookname:abcwriter:dpno:999
id:1109bookname:acbwriter:ddpno:80
id:1110bookname:acbwriter:ddpno:80

------解决方案--------------------
int mid = -1;
...........
ResultSet rs = st.getGeneratedKeys();
if(rs.next())
mid = rs.getInt(1);
System.out.println(mid)

看这几句就知道mid为何为0了
getGeneratedKeys自动获取主键的方法
因为结果集不为null
rs能获取key为1所以
mid自动增长 +1
------解决方案--------------------
理解错了 不好意思
应该是mid是表示第几列。
rs.getInt(1), 得到是第0列 所以mid = 0
------解决方案--------------------
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="user" extends="struts-default">

<action name="saveUser" class="saveUserAction">
<!-- class="saveUserAction" 别名 和spring 的配置文件下的id对应 -->
<!-- 重定向到另一个action -->
<!-- type可以是
dispatcher请求转发:保护jsp路劲,用户看不到
redirect响应重定向:
train:请求转发到另一个action
redirect-action:响应重定向到另一个action
jsf
jfc
-->
<result name="success" type="redirect">
listUser.action
</result>
<result name="input">/save.jsp</result>
</action>

<action name="listUser" class="listUserAction">
<result>/list.jsp</result>
</action>

<action name="deleteUser" class="removeUserAction">
<result name="success" type="redirect">listUser.action</result>
</action>

<action name="updatePUser" class="updatePUserAction">
<result name="success">/update.jsp</result>
</action>
<action name="updateUser" class="updateUserAction">
<result name="success" type="redirect">listUser.action</result>
<result name="input">/update.jsp</result>
</action>

<action name="