1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

  2. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[SQL] How to stop auto-increment from assigning an ID in SQL when inserting a new record via...

Discussão em 'Outras Linguagens' iniciado por Stack, Novembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    I'm currently building an API to add new items to my database, and I have a function to insert a new item. However, every time I add a new item, the database ignores the ID I provide and generates a unique ID automatically. My professor mentioned that this happens because each column in the database is set to auto-increment, which causes the database to automatically assign a new ID during the insert. Is there a way to disable the auto-increment behavior for specific inserts so that I can use the ID I provide?

    The API is below:

    `. [HttpPost(template:"AddTeacher")]
    public IActionResult AddTeacher([FromBody]Teacher TeacherData)
    {
    using (MySqlConnection Connection = _context.AccessDatabase())
    {
    Connection.Open();

    MySqlCommand Command = Connection.CreateCommand();

    Command.CommandText = "insert into teachers (teacherfname, teacherlname, ) values (@teacherfname, @teacherlname)";
    Command.Parameters.AddWithValue("@teacherfname", TeacherData.TeacherFName);
    Command.Parameters.AddWithValue("@teacherlname", TeacherData.TeacherLName);

    Command.ExecuteNonQuery();
    int insertedId = Convert.ToInt32(Command.LastInsertedId);
    return Ok(insertedId);
    }. `


    I tried explicitly setting the ID value when inserting a new record into the database. I expected the database to use the ID I provided, but instead, it ignored my ID and generated a new one automatically, likely due to the column being set to auto-increment.

    Continue reading...

Compartilhe esta Página