SQL Server数据库查询刚插入的行的ID值

问题描述:

SQL Server数据库表 tb_1 id为自增长标识,怎样在插入的同时返回刚插入行id?

方法:

“@@IDENTITY”

示例如下:

返回值:1001 (既刚插入行ID)

 insert into tb_1
 values('名字','性别')
 select @@IDENTITY  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供 Java 连接 SQL Server 数据库并执查询插入操作的代码范例。请确保您已经安装了 SQL Server,并且已经下载了相应的 SQL Server JDBC 驱动程序。以下是示例代码: ``` import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SQLServerExample { public static void main(String[] args) { // JDBC driver name and database URL String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; String DB_URL = "jdbc:sqlserver://localhost:1433;databaseName=mydatabase"; // Database credentials String USER = "username"; String PASS = "password"; Connection conn = null; Statement stmt = null; try { // Register JDBC driver Class.forName(JDBC_DRIVER); // Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); // Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, name, age FROM mytable"; ResultSet rs = stmt.executeQuery(sql); // Extract data from result set while (rs.next()) { // Retrieve by column name int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); // Display values System.out.print("ID: " + id); System.out.print(", Name: " + name); System.out.println(", Age: " + age); } // Insert a record System.out.println("Inserting a record into the table..."); sql = "INSERT INTO mytable (id, name, age) VALUES (4, 'John', 30)"; int rowsInserted = stmt.executeUpdate(sql); if (rowsInserted > 0) { System.out.println("A new record has been inserted."); } // Clean-up environment rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // Finally block used to close resources try { if (stmt != null) { stmt.close(); } } catch (SQLException se2) { } // nothing we can do try { if (conn != null) { conn.close(); } } catch (SQLException se) { se.printStackTrace(); } // end finally try } // end try System.out.println("Goodbye!"); } // end main } ``` 在这个例子中,我们首先定义了数据库的 URL,用户名和密码。然后我们注册了 JDBC 驱动程序,打开了一个连接,并创建了一个 Statement 对象。接下来,我们执了一个查询,并从结果集中提取了数据。最后,我们插入了一条记录,并关闭了连接。请注意,您需要将代码中的用户名、密码、数据库名、表名和列名更改为您自己的

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值