菜菜求取主键值插入外键中的方法
import java.sql.*;
import sun.security.action.GetIntegerAction;
public class preparedStatementTest {
public static void main(String[] args){
Connection conn=null;
ResultSet rs=null;
PreparedStatement pstmt=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(
"jdbc:mysql://localhost/bbs?user=root&password=mysqlcom");
//t2表中主键,nid,自增
String sql="insert into t2(nid,tname)values(null,?)";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, "aa");
pstmt.executeUpdate();
//查找t2表中主键nid的值
sql="select last_insert_id()";
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1));
}
//t1表中nameId为外键
sql="insert into t1(id,nameid,nam)values(null,?,?)";
pstmt=conn.prepareStatement(sql);
//rs.getInt(1)出错.求取上面主键值的方法
pstmt.setInt(1,rs.getInt(1));
pstmt.setString(2,"bb");
pstmt.executeUpdate();
}catch(
ClassNotFoundException e){
e.printStackTrace();
}catch(
SQLException e){
e.printStackTrace();
}finally{
try{
if(rs!=null){
pstmt.close();
rs=null;
}
if(pstmt!=null){
pstmt.close();
pstmt=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
控制台输出:
20
java.sql.SQLException: After end of result set
at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:841)
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2674)
at preparedStatementTest.main(preparedStatementTest.java:32)
------最佳解决方案-------------------- while(rs.next()){
//t1表中nameId为外键
sql="insert into t1(id,nameid,nam)values(null,?,?)";
pstmt=conn.prepareStatement(sql);
//rs.getInt(1)出错.求取上面主键值的方法
pstmt.setInt(1,rs.getInt(1));
pstmt.setString(2,"bb");
pstmt.executeUpdate();
}
扩大范围
LAST_INSERT_ID() 返回的是一个记录、
所以用if(rs.next()){} 就可以了、