我想使用Java中的JDBC在数据库(在我的情况下为Microsoft SQL Server)中INSERT
一条记录。 同时,我想获取插入ID。 如何使用JDBC API实现此目的?
#1楼
我正在使用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)
{
}
}
}
这个解决方案对我有用!
我希望这有帮助!
#2楼
如果它是自动生成的密钥,则可以为此使用Statement#getGeneratedKeys()
。 您需要在与用于INSERT
Statement
相同的Statement
上调用它。 首先,您需要使用Statement.RETURN_GENERATED_KEYS
创建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,可以在同一事务中的INSERT
之后直接使用RETURNING
子句或SELECT CURRVAL(sequencename)
(或执行此操作的任何特定于DB的语法SELECT CURRVAL(sequencename)
调用CallableStatement
,以获取最后生成的密钥。 另请参阅此答案 。
#3楼
使用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。
#4楼
创建生成的列
String generatedColumns[] = { "ID" };
将此生成的列传递给您的声明
PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns);
使用
ResultSet
对象在Statement上获取GeneratedKeysResultSet rs = stmtInsert.getGeneratedKeys(); if (rs.next()) { long id = rs.getLong(1); System.out.println("Inserted ID -" + id); // display inserted record }
#5楼
Connection cn = DriverManager.getConnection("Host","user","pass");
Statement st = cn.createStatement("Ur Requet Sql");
int ret = st.execute();
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3167914