-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How can I get last insert id for MySQL #127
Comments
I have the same issue, and |
actually i use |
It's my mistake, |
Currently, this is the best option: SELECT LAST_INSERT_ID() as id But I'm sure we can do better. Currently Thoughts @abonander ? |
I can't find where in the protocol it gives the last inserted ID. |
@abonander MySQL gives it in the OK packet. |
there are a couple of ways to approach this:
|
I've been thinking this over. trait Executor {
fn execute(&mut self, statement: impl Execute) -> impl Statement;
// [...]
}
trait Statement where Self: Future<Output = crate::Result<()>> {
type Database: Database;
async fn affected_rows(self) -> crate::Result<u64>;
fn fetch(self) -> impl Cursor;
async fn fetch_one<T>(self) -> crate::Resul<T>;
async fn fetch_scalar<T>(self) -> crate::Result<T>;
}
impl Statement for MySqlStatement { ... }
impl MySqlStatement {
async fn last_insert_id(self) -> crate::Result<u64>;
}
Unresolved question:
|
Wrap let username = "test";
let mut db_conn_with_transaction = db_pool.begin().await.unwrap();
sqlx::query("INSERT INTO users (username) VALUES (?);")
.bind(username)
.execute(&mut db_conn_with_transaction)
.await
.unwrap();
let last_insert_id = sqlx::query_as::<_, (u32,)>("SELECT LAST_INSERT_ID();")
.fetch_one(&mut db_conn_with_transaction)
.await
.unwrap()
.0;
dbg!(last_insert_id);
assert_ne!(last_insert_id, 0);
db_conn_with_transaction.commit().await.unwrap(); In MySQL general log
|
Please see #508 and leave feedback |
Now available on master |
Cross link: https://stackoverflow.com/q/63755877/7076153 |
use Google search will be here, so add a little example here sqlx::query("insert into xxx ...")
.execute(&db)
.await?
.last_insert_id(); for MySQL |
For mssql, how to get the inserted id value? |
In PostgreSQL we can return the id after inserting record such as
INSERT INTO users ( username, email, password ) VALUES ( $1, $2, $3 ) RETURNING id, username, email
But the syntax doesn't work in MySQL and MySQL doesn't have any equivalent syntax. So I have to make a separate select to get last insert id
SELECT LAST_INSERT_ID()
Is there any more convenient way to do this?
The text was updated successfully, but these errors were encountered: