今天上网查资料写了一个在mssql获得刚插入字段的值(该字段是自增的),但返回的老是零,为什么,请大家帮忙看一下?
数据库表是 message(int id,varchar name) 其中id是自增的
代码如下:
GetIdentity.java
数据库表是 message(int id,varchar name) 其中id是自增的
代码如下:
GetIdentity.java
1
package com.study.dbo;
2
3
import java.sql.Connection;
4
import java.sql.DriverManager;
5
import java.sql.PreparedStatement;
6
import java.sql.ResultSet;
7
import java.sql.SQLException;
8
import java.sql.Statement;
9
10
public class GetIdentity {
11
12
public static void main(String[] args) {
13
14
Connection conn=null;
15
try {
16
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
17
conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=demo;SelectMethod=Cursor;User=sa;Password=sa");
18
conn.setAutoCommit(false);
19
String insert="insert into message values('wuguoming2010')";
20
PreparedStatement prestmt=conn.prepareStatement(insert);
21
prestmt.execute();
22
String sql="select SCOPE_IDENTITY()";
23
// String sql="select @@identity";
24
prestmt=conn.prepareStatement(sql);
25
ResultSet rs=prestmt.executeQuery();
26
long identity=0;
27
while (rs.next()) {
28
System.out.println(rs.getLong(1));
29
identity=rs.getLong(1);
30
}
31
conn.commit();
32
System.out.println(identity);
33
} catch (ClassNotFoundException e) {
34
// TODO Auto-generated catch block
35
e.printStackTrace();
36
}
37
catch (SQLException sqle) {
38
// TODO Auto-generated catch block
39
sqle.printStackTrace();
40
}
41
}
42
}
打印出来的老是零?为什么?请大家看一下,帮个忙,谢谢!!
package com.study.dbo;2

3
import java.sql.Connection;4
import java.sql.DriverManager;5
import java.sql.PreparedStatement;6
import java.sql.ResultSet;7
import java.sql.SQLException;8
import java.sql.Statement;9

10
public class GetIdentity {11

12
public static void main(String[] args) {13
14
Connection conn=null;15
try {16
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");17
conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=demo;SelectMethod=Cursor;User=sa;Password=sa");18
conn.setAutoCommit(false);19
String insert="insert into message values('wuguoming2010')";20
PreparedStatement prestmt=conn.prepareStatement(insert);21
prestmt.execute();22
String sql="select SCOPE_IDENTITY()";23
// String sql="select @@identity";24
prestmt=conn.prepareStatement(sql);25
ResultSet rs=prestmt.executeQuery();26
long identity=0;27
while (rs.next()) {28
System.out.println(rs.getLong(1));29
identity=rs.getLong(1);30
}31
conn.commit();32
System.out.println(identity);33
} catch (ClassNotFoundException e) {34
// TODO Auto-generated catch block35
e.printStackTrace();36
}37
catch (SQLException sqle) {38
// TODO Auto-generated catch block39
sqle.printStackTrace();40
}41
}42
}



浙公网安备 33010602011771号