How do I get the last id inserted in ASP.NET?

4

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

  

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

Why 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)
);
    
asked by anonymous 13.05.2014 / 02:28

2 answers

1

If you are 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 !!!
    
13.05.2014 / 02:36
0

If you want to get the last id entered 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

    
13.05.2014 / 02:49