E
E
Evgeny Semashko2020-06-22 15:02:35
SQL
Evgeny Semashko, 2020-06-22 15:02:35

How to get last id from database?

I need to take the last recorded Id from the database and increment it (naturally I can do this) in order to use the new Id to insert a record into the database.
That is, I need to create a query that will pull the last Id from the database and write it to a variable

String^ constr = "Data Source=DESKTOP-QN31D90;Initial Catalog=Online_Pharma;Integrated Security=True;Pooling=False";
    SqlConnection^ con = gcnew SqlConnection(constr);

    
    String^ name = nameBox->Text;
    String^ type = typeBox->Text;
    int Price = Int32::Parse(priceBox->Text);
    
    SqlCommand^ cmd = gcnew SqlCommand("INSERT INTO Medicines VALUES(" /*сюда нужно вставить инкрементированный Id*/  ","  + name + ",'" + type + "','" + Price + "','" + comboBox1->SelectedItem + "')", con);
    SqlDataReader^ dr;
    con->Open();
    dr = cmd->ExecuteReader();
    MessageBox::Show("Succesful");
    con->Close();


This is necessary in order to fill in the first field with an auto-incrementing Id, because when I try to insert data into the database, I get this , since the first field requires a number and skips only if I enter a number

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lazy @BojackHorseman, 2020-06-22
@evgenysemashko

engines do it themselves. also for competing
SQL queries AUTO INCREMENT Field

A
Arseniy Rumyantsev, 2020-06-30
@arsrum

"select max(id) from Medicines;"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question