Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi..
I m Connecting to mysql using c#.I want to get last inserted id.I want to use that last inserted id+1 when next time i will run application..
But whenever i will run my application get id 1 everytime..
Thanks..
Posted
Comments
Aniket Yadav 27-Sep-13 1:46am    
Will you please explain in detail what exactly you want to achieve? Example will be more descriptive
Rohini Shirke 27-Sep-13 1:59am    
I have mysql table such as
studinfo
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| studid | int(11) | NO | PRI | NULL | auto_increment |
| firstname | varchar(20) | YES | | NULL | |
| lastname | varchar(20) | YES | | NULL | |
| address | varchar(50) | YES | | NULL | |
| Image | longblob | YES | | NULL | |
+-----------+-------------+------+-----+---------+----------------+
I will insert value in this table through C# application by writing
string cmdText = "Insert into studinfo values(@ID,@First,@Last,@address,@Image)";
cmd = new MySqlCommand(cmdText, con);
cmd.Parameters.AddWithValue("@ID",?);
cmd.Parameters.AddWithValue("@First", txtFirstName.Text);
cmd.Parameters.AddWithValue("@Last", txtLastName.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Image", imagedata);
int rowaffected = cmd.ExecuteNonQuery();
In place of "?" what should i will write to do insertion sucessful..

1 solution

This is to get the last inserted id from the database table when the ID is Auto-increment.
C#
string InsertedId = "";
RowAffected = cmd.ExecuteCommand();

//After inserting the record you call this function to get the last inserted id from the table.
string query="SELECT LAST_INSERT_ID() FROM studinfo";
if (RowAffected > 0)
       cmd= new MySqlCommand(query, Con);
       InsertedId = cmd.ExecuteScalar();


This is another way to get the lastinserted from the table.
C#
string filename = txtImage.Text;
        byte[] imagedata;
        fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
        br = new BinaryReader(fs);
        imagedata = br.ReadBytes((int)fs.Length);
        br.Close();
        fs.Close();

        string query = "SELECT max(ID) FROM studinfo";
        cmd = new MySqlCommand(query, con);
        InsertedId = cmd.ExecuteScalar();
        //When the first time executes InsertedId will be null or empty since there wont be any records stored in the table
        if (InsertedId == "")
        {
            //Assign default value as 1.
            //then pass it as parameters
            InsertedId = 1;
        }
        else
        {
            //it will return the last inserted id you make it plus 1 so that it will get increment to get a new id.
            //then pass it as parameters
            InsertedId = InsertedId + 1;
        }

        string cmdText = "Insert into studinfo values(@ID,@First,@Last,@address,@Image)";
        cmd = new MySqlCommand(cmdText, con);
        cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(InsertedId));
        cmd.Parameters.AddWithValue("@First", txtFirstName.Text);
        cmd.Parameters.AddWithValue("@Last", txtLastName.Text);
        cmd.Parameters.AddWithValue("@address", txtAddress.Text);
        cmd.Parameters.AddWithValue("@Image", imagedata);
        int rowaffected = cmd.ExecuteNonQuery();
        //string query = "SELECT LAST_INSERT_ID() FROM studinfo";
        if (rowaffected > 0)
        {
            MessageBox.Show("Inserted sucessfully");
            Clear();
            txtFirstName.Focus();
        }


Hope this helps you.
 
Share this answer
 
v5
Comments
Rohini Shirke 27-Sep-13 2:39am    
hi Thomas..
Thanks for reply but i will give error in follwing statement
InsertedId = cmd.ExecuteScalar("SELECT LAST_INSERT_ID() FROM studinfo");
error will be :"No overload for 'ExecuteScalar' takes 1 arguement"
Thomas ktg 27-Sep-13 3:07am    
Updated my solution look at this.
Rohini Shirke 27-Sep-13 3:20am    
Hello Sir..
I have write this code but it will give error "Input string is not in correct format"
try
{
con = new MySqlConnection(cs);
con.Open();
if (txtFirstName.Text.Length > 0 && txtLastName.Text.Length > 0)
{
string filename = txtImage.Text;
byte[] imagedata;
fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
imagedata = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();



string cmdText = "Insert into studinfo values(@ID,@First,@Last,@address,@Image)";
cmd = new MySqlCommand(cmdText, con);


cmd.Parameters.AddWithValue("@ID",Convert.ToInt32(InsertedId));
cmd.Parameters.AddWithValue("@First", txtFirstName.Text);
cmd.Parameters.AddWithValue("@Last", txtLastName.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Image", imagedata);
int rowaffected = cmd.ExecuteNonQuery();
string query = "SELECT LAST_INSERT_ID() FROM studinfo";
if (rowaffected > 0)
{
cmd = new MySqlCommand(query, con);
InsertedId = (string)cmd.ExecuteScalar();

MessageBox.Show("Inserted sucessfully");

Clear();
txtFirstName.Focus();
}

}
else
{
MessageBox.Show("Incomplete Data", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtFirstName.Focus();
}


}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
finally
{
con.Close();
}
Thomas ktg 27-Sep-13 3:30am    
I do not know whether I have understood wrong or you dont understand what i have given.
If the record is inserted only then you can get the last inserted id as per the solution i have given.
And most important thing is that you using the insertid before it is being executed from the database then how can you assign the value?
Ok tell what is the datatype of ID in the database?
Thomas ktg 27-Sep-13 4:11am    
I have updated the solution from your point of view. Please let me know if there is any doubt.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900