public class Test { public static Connection init(){
Connection conn = null;
String url ="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=ccc";
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
conn = DriverManager.getConnection(url,"sa","admin");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException时发生异常");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SQLException 时发生异常");
e.printStackTrace();
}
return conn;
} public static void main(String[] args) {
Connection conn = init();
ResultSet rs = null;
try {
String sql = "INSERT INTO dd (ddd) VALUES ('221111') select SCOPE_IDENTITY() as id";
//PreparedStatement pstm = conn.prepareStatement(sql);
//pstm.executeUpdate();
Statement pstm = conn.createStatement();
boolean ok = pstm.execute(sql);
System.out.println(ok);
//rs = pstm.getGeneratedKeys();
//System.out.println(rs);
//System.out.println("222");
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
conn.close();
} catch (SQLException e) {
System.out.println("类: 方法: 执行: 发生:SQLException异常");
}
}
}}
Connection conn = null;
String url ="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=ccc";
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
conn = DriverManager.getConnection(url,"sa","admin");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException时发生异常");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SQLException 时发生异常");
e.printStackTrace();
}
return conn;
} public static void main(String[] args) {
Connection conn = init();
ResultSet rs = null;
try {
String sql = "INSERT INTO dd (ddd) VALUES ('221111') select SCOPE_IDENTITY() as id";
//PreparedStatement pstm = conn.prepareStatement(sql);
//pstm.executeUpdate();
Statement pstm = conn.createStatement();
boolean ok = pstm.execute(sql);
System.out.println(ok);
//rs = pstm.getGeneratedKeys();
//System.out.println(rs);
//System.out.println("222");
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
conn.close();
} catch (SQLException e) {
System.out.println("类: 方法: 执行: 发生:SQLException异常");
}
}
}}
PreparedStatement pstm = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
pstm.executeUpdate();
rs = pstm..getGeneratedKeys();
while(rs.next()) {
int id = rs.getInt("id")//表的字段名字也可以用字段下标值
}
at com.Test.main(Test.java:42)
PreparedStatement pstm = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
pstm.executeUpdate();
ResultSet res = pstm.getGeneratedKeys();
res.next();
int Rtn=res.getInt(1);
Close();
return Rtn;
这样可以的,我试过了。