在使用相同连接的多个查询中获取最后插入的ID,可以通过以下几种方式实现:
LAST_INSERT_ID()
函数获取最后插入的ID。示例代码:INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2');
SELECT LAST_INSERT_ID();RETURNING
关键字获取最后插入的ID。示例代码:INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2') RETURNING id;RETURNING INTO
语句获取最后插入的ID。示例代码:DECLARE
last_id NUMBER;
BEGIN
INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2') RETURNING id INTO last_id;
DBMS_OUTPUT.PUT_LINE('Last Inserted ID: ' || last_id);
END;last_inserted_id
表获取最后插入的ID。 conn = mysql.connector.connect(host='localhost', user='username', password='password', database='database')
cursor = conn.cursor()
insert_query = "INSERT INTO table_name (column1, column2) VALUES (%s, %s)"
values = ('value1', 'value2')
cursor.execute(insert_query, values)
last_insert_id = cursor.lastrowid
print("Last Inserted ID:", last_insert_id)
conn.commit()
cursor.close()
conn.close()
```
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/database", "username", "password");
Statement stmt = conn.createStatement();
String insertQuery = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
stmt.executeUpdate(insertQuery, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
int lastInsertId = rs.getInt(1);
System.out.println("Last Inserted ID: " + lastInsertId);
}
stmt.close();
conn.close();
```
以上是几种常见的获取最后插入ID的方法,具体选择哪种方法取决于使用的数据库和编程语言。
领取专属 10元无门槛券
手把手带您无忧上云