Adding data from c#form (visual studio) to mysql database and need to retrieve new record ID back on to form

StackOverflow https://stackoverflow.com/questions/17065816

سؤال

I am very very new to programming (about a week) and I am currently doing a project on c#, sql for college. I have done well so far and able to add, delete and update rows on to mysql from visual studio form. I would like a label (label5) to be updated with the new ID code from new inserted row when I click the add button. So I can then take that digit and move on with some more programming work.

Heres My code for when I hit that button.. I've been on this 5 hours and ran out online resources (or I just don't understand those resources I picked up something like LastInsertedID but it just doesn't work for me)

 private void button4_Click(object sender, EventArgs e)
    {

        string constring = "datasource=localhost;port=***;username=***;password=***";
        string Query = "insert into cars.customers (FirstName, Surname,TelephoneNo,Address1, Address2, Town, PostCode) values('" + this.FName_txt.Text + "','" + this.Surname_txt.Text + "','" + this.TelNo_txt.Text + "','" + this.Address1.Text + "','" + this.Address2.Text + "','" + this.Town_txt.Text + "','" + this.PostCode_txt.Text + "');";
        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
        MySqlDataReader myReader;

        try
        {
            conDataBase.Open();
            myReader = cmdDataBase.ExecuteReader();
            MessageBox.Show("Saved Customer Details");
            while (myReader.Read())
            {
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

I understand that my terminology is pretty grim, so I hope this is understandable Idiots guide is preferable, thanks!

هل كانت مفيدة؟

المحلول

You can grab the command.LastInsertedId e.g.

MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
cmdDataBase.ExecuteNonQuery();
var lastId = cmdDataBase.LastInsertedId;

// Assign to label
label5.Text = lastId.ToString();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top