Answers:
如果它是自动生成的密钥,那么您可以使用Statement#getGeneratedKeys()
它。您需要Statement
使用与用于相同的名称进行调用INSERT
。您首先需要使用创建语句Statement.RETURN_GENERATED_KEYS
用于通知JDBC驱动程序以返回键。
这是一个基本示例:
public void create(User user) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_INSERT,
Statement.RETURN_GENERATED_KEYS);
) {
statement.setString(1, user.getName());
statement.setString(2, user.getPassword());
statement.setString(3, user.getEmail());
// ...
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
user.setId(generatedKeys.getLong(1));
}
else {
throw new SQLException("Creating user failed, no ID obtained.");
}
}
}
}
请注意,您是否依赖JDBC驱动程序。当前,大多数最新版本都可以使用,但是如果我没错,Oracle JDBC驱动程序仍然有些麻烦。MySQL和DB2已经支持它很久了。PostgreSQL不久前就开始支持它。我从未评论过MSSQL,因为我从未使用过它。
对于Oracle,您可以在同一事务中直接在CallableStatement
with之后调用with RETURNING
子句或SELECT CURRVAL(sequencename)
(或执行此操作的任何特定于DB的特定语法)INSERT
以获取最后生成的密钥。另请参阅此答案。
创建生成的列
String generatedColumns[] = { "ID" };
将此生成的列传递给您的声明
PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns);
使用ResultSet
对象在语句上获取GeneratedKeys
ResultSet rs = stmtInsert.getGeneratedKeys();
if (rs.next()) {
long id = rs.getLong(1);
System.out.println("Inserted ID -" + id); // display inserted record
}
我正在从基于单线程JDBC的应用程序中访问Microsoft SQL Server 2008 R2,并撤回了最后一个ID,而不使用RETURN_GENERATED_KEYS属性或任何PreparedStatement。看起来像这样:
private int insertQueryReturnInt(String SQLQy) {
ResultSet generatedKeys = null;
int generatedKey = -1;
try {
Statement statement = conn.createStatement();
statement.execute(SQLQy);
} catch (Exception e) {
errorDescription = "Failed to insert SQL query: " + SQLQy + "( " + e.toString() + ")";
return -1;
}
try {
generatedKey = Integer.parseInt(readOneValue("SELECT @@IDENTITY"));
} catch (Exception e) {
errorDescription = "Failed to get ID of just-inserted SQL query: " + SQLQy + "( " + e.toString() + ")";
return -1;
}
return generatedKey;
}
该博客文章很好地隔离了三个主要的SQL Server“ last ID”选项:http : //msjawahar.wordpress.com/2008/01/25/how-to-find-the-last-identity-value-inserted-in-the -sql-server / -不需要其他两个。
使用时遇到“不受支持的功能”错误Statement.RETURN_GENERATED_KEYS
,请尝试以下操作:
String[] returnId = { "BATCHID" };
String sql = "INSERT INTO BATCH (BATCHNAME) VALUES ('aaaaaaa')";
PreparedStatement statement = connection.prepareStatement(sql, returnId);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet rs = statement.getGeneratedKeys()) {
if (rs.next()) {
System.out.println(rs.getInt(1));
}
rs.close();
}
BATCHID
自动生成的ID 在哪里。
BATCHID
我正在使用SQLServer 2008,但是我有一个开发限制:我不能使用新的驱动程序,必须使用“ com.microsoft.jdbc.sqlserver.SQLServerDriver”(我不能使用“ com.microsoft.sqlserver.jdbc” .SQLServerDriver”)。
这就是为什么该解决方案为我conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
抛出java.lang.AbstractMethodError的原因。在这种情况下,我发现一个可能的解决方案是Microsoft建议的旧解决方案:
如何使用JDBC检索@@ IDENTITY值
import java.sql.*;
import java.io.*;
public class IdentitySample
{
public static void main(String args[])
{
try
{
String URL = "jdbc:microsoft:sqlserver://yourServer:1433;databasename=pubs";
String userName = "yourUser";
String password = "yourPassword";
System.out.println( "Trying to connect to: " + URL);
//Register JDBC Driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
//Connect to SQL Server
Connection con = null;
con = DriverManager.getConnection(URL,userName,password);
System.out.println("Successfully connected to server");
//Create statement and Execute using either a stored procecure or batch statement
CallableStatement callstmt = null;
callstmt = con.prepareCall("INSERT INTO myIdentTable (col2) VALUES (?);SELECT @@IDENTITY");
callstmt.setString(1, "testInputBatch");
System.out.println("Batch statement successfully executed");
callstmt.execute();
int iUpdCount = callstmt.getUpdateCount();
boolean bMoreResults = true;
ResultSet rs = null;
int myIdentVal = -1; //to store the @@IDENTITY
//While there are still more results or update counts
//available, continue processing resultsets
while (bMoreResults || iUpdCount!=-1)
{
//NOTE: in order for output parameters to be available,
//all resultsets must be processed
rs = callstmt.getResultSet();
//if rs is not null, we know we can get the results from the SELECT @@IDENTITY
if (rs != null)
{
rs.next();
myIdentVal = rs.getInt(1);
}
//Do something with the results here (not shown)
//get the next resultset, if there is one
//this call also implicitly closes the previously obtained ResultSet
bMoreResults = callstmt.getMoreResults();
iUpdCount = callstmt.getUpdateCount();
}
System.out.println( "@@IDENTITY is: " + myIdentVal);
//Close statement and connection
callstmt.close();
con.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
try
{
System.out.println("Press any key to quit...");
System.in.read();
}
catch (Exception e)
{
}
}
}
这个解决方案对我有用!
我希望这有帮助!
除了发表评论,我只想回答帖子。
columnIndexes «您可以使用prepareStatement函数,该函数接受columnIndexes和SQL语句。 如果columnIndexes允许的常量标志是Statement.RETURN_GENERATED_KEYS 1或Statement.NO_GENERATED_KEYS [2],则SQL语句可能包含一个或多个“?” IN参数占位符。
句法 ”
Connection.prepareStatement(String sql, int autoGeneratedKeys)
Connection.prepareStatement(String sql, int[] columnIndexes)
例:
PreparedStatement pstmt =
conn.prepareStatement( insertSQL, Statement.RETURN_GENERATED_KEYS );
columnNames « 列出columnNames之类的'id', 'uniqueID', ...
。在目标表中包含应返回的自动生成的键。如果SQL语句不是INSERT
语句,驱动程序将忽略它们。
句法 ”
Connection.prepareStatement(String sql, String[] columnNames)
例:
String columnNames[] = new String[] { "id" };
PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
完整示例:
public static void insertAutoIncrement_SQL(String UserName, String Language, String Message) {
String DB_URL = "jdbc:mysql://localhost:3306/test", DB_User = "root", DB_Password = "";
String insertSQL = "INSERT INTO `unicodeinfo`( `UserName`, `Language`, `Message`) VALUES (?,?,?)";
//"INSERT INTO `unicodeinfo`(`id`, `UserName`, `Language`, `Message`) VALUES (?,?,?,?)";
int primkey = 0 ;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(DB_URL, DB_User, DB_Password);
String columnNames[] = new String[] { "id" };
PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
pstmt.setString(1, UserName );
pstmt.setString(2, Language );
pstmt.setString(3, Message );
if (pstmt.executeUpdate() > 0) {
// Retrieves any auto-generated keys created as a result of executing this Statement object
java.sql.ResultSet generatedKeys = pstmt.getGeneratedKeys();
if ( generatedKeys.next() ) {
primkey = generatedKeys.getInt(1);
}
}
System.out.println("Record updated with id = "+primkey);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
也可以将其与normal一起使用Statement
(而不仅仅是PreparedStatement
)
Statement statement = conn.createStatement();
int updateCount = statement.executeUpdate("insert into x...)", Statement.RETURN_GENERATED_KEYS);
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
return generatedKeys.getLong(1);
}
else {
throw new SQLException("Creating failed, no ID obtained.");
}
}
就我而言->
ConnectionClass objConnectionClass=new ConnectionClass();
con=objConnectionClass.getDataBaseConnection();
pstmtGetAdd=con.prepareStatement(SQL_INSERT_ADDRESS_QUERY,Statement.RETURN_GENERATED_KEYS);
pstmtGetAdd.setString(1, objRegisterVO.getAddress());
pstmtGetAdd.setInt(2, Integer.parseInt(objRegisterVO.getCityId()));
int addId=pstmtGetAdd.executeUpdate();
if(addId>0)
{
ResultSet rsVal=pstmtGetAdd.getGeneratedKeys();
rsVal.next();
addId=rsVal.getInt(1);
}
如果您使用的是Spring JDBC,则可以使用Spring的GeneratedKeyHolder类获取插入的ID。
看到这个答案... 如何使用Spring Jdbctemplate.update(String sql,obj ... args)插入ID
Connection cn = DriverManager.getConnection("Host","user","pass");
Statement st = cn.createStatement("Ur Requet Sql");
int ret = st.execute();
createStatement
方法Connection
不要期望任何参数。2. execute
from 的方法Statement
期望带查询的字符串。3.该execute
方法返回:true
如果第一个结果是ResultSet
对象,则返回;否则返回0 。false
如果是更新计数或没有结果。docs.oracle.com/javase/7/docs/api/java/sql/…–
String sql = "INSERT INTO 'yash'.'mytable' ('name') VALUES (?)"; int primkey = 0 ; PreparedStatement pstmt = con.prepareStatement(sql, new String[] { "id" }/*Statement.RETURN_GENERATED_KEYS*/); pstmt.setString(1, name); if (pstmt.executeUpdate() > 0) { java.sql.ResultSet generatedKeys = pstmt.
。if (generatedKeys.next()) primkey = generatedKeys.getInt(1); }