How to get the last id inserted in Asp.net?

Asked

Viewed 576 times

4

I’m making a website on ASP.NET, and I need to register a user/client. The question is: as soon as I enter the values in the table users, I need to get the id of this table and use in the table end_user (user address table) to register the rest of user information. How can I do this? I tried to use the last_insert_id(), but makes a mistake:

You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'SELECT last_insert_id() = NULL' at line 1

Because it gives null?

The tables:

CREATE TABLE users (
id_user INT NOT NULL AUTO_INCREMENT,
nome_us TEXT NOT NULL,
snome_us TEXT NOT NULL,
rg_us TEXT NOT NULL,
cpf_us TEXT NOT NULL,
email_us TEXT NOT NULL,
fone_us TEXT DEFAULT NULL,

PRIMARY KEY(id_user)
);

CREATE TABLE end_user
(
id_user INT NOT NULL,
cep_us TEXT NOT NULL,
num_us TEXT NOT NULL,
comp_us TEXT,

FOREIGN KEY(id_user) REFERENCES users(id_user),

PRIMARY KEY(id_user)
);

2 answers

1

If using Mysqlclient for C# or VB.Net it is already implemented:

Example

var conexao = new MySql.Data.MySqlClient.MySqlConnection();
MySql.Data.MySqlClient.MySqlCommand co = new MySql.Data.MySqlClient.MySqlCommand("insert into ...", conexao);
co.ExecuteNonQuery();
long t = co.LastInsertedId; // recuperando aqui depois de executar o SQL de Insert !!!

0

If you want to get the last id inserted directly into the database, you can do:

INSERT INTO users (nome_us,...) VALUES ('Nome',...);
SET @last_id_in_users = LAST_INSERT_ID();
INSERT INTO end_user (id_user,...) VALUES (@last_id_in_users,...);

SQL Fiddle Example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.