Skip to content
Advertisement

How to convert last insert id into string?

I have a create account page and on the page I have one button to insert all the details into two seperate tables one of the tables Pictures is dependant on the User table 1:1 relationship via UserID.

I have written some code to try get the last insert id so I can insert into the pictures table:

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            try
            {
                OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();

                OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme, username, password) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "')", cn);
                OdbcCommand sc = new OdbcCommand("SELECT LAST_INSERT_ID()", cn);
                //convert LAST INSERT into string theUserId

                string filenameDB = Path.GetFileName(FileUpload1.FileName);
                string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
                FileUpload1.SaveAs(fileuploadpath);
                string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
                Label10.Text = "Upload status: File uploaded!";
                OdbcCommand cm = new OdbcCommand("INSERT INTO Pictures (picturepath, UserId) VALUES ('" + fileuploadpaths + "', " + theUserId + ")", cn);

                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Label10.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;

            }
            //e.Authenticated = true;
            //Response.Redirect("Login.aspx");
            // Event useradded is true forward to login
        }
    }
}

Not sure if this is correct and I also need to know how to convert the select statement into a string so I can retrieve the UserID from the User table, see database structure:

enter image description here

EDIT

protected void Button1_Click(object sender, EventArgs e)
{
    if (FileUpload1.HasFile)
    {
        try
        {
            OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");


            OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme, username, password) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "')SELECT LAST_INSERT_ID()", cn);
            //OdbcCommand sc = new OdbcCommand("SELECT LAST_INSERT_ID()", cn);
            //convert LAST INSERT into string theUserId
            //using (DataTable dt = DataTier.ExecuteQuery(cmd))
            ////error for datatable and datatier
            //if (dt.Rows.Count == 1)
            //{
            //    //Read the new ID from the record that has just been inserted
            //    string theUserId = dt.Rows[0]["UserID"].ToString();
            using (OdbcDataReader reader = cmd.ExecuteReader())
            {
           
            string theUserId = String.Format("{0}", reader.GetString(0));

            string filenameDB = Path.GetFileName(FileUpload1.FileName);
            string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + Path.GetFileName(FileUpload1.FileName);
            FileUpload1.SaveAs(fileuploadpath);
            string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") + filenameDB;
            Label10.Text = "Upload status: File uploaded!";
            OdbcCommand cm = new OdbcCommand("INSERT INTO Pictures (picturepath, UserId) VALUES ('" + fileuploadpaths + "', " + theUserId + ")", cn);
            cn.Open();
            cmd.ExecuteNonQuery();
            }
        }
        catch (Exception ex)
        {
            Label10.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;

        }
        //e.Authenticated = true;
        //Response.Redirect("Login.aspx");
        // Event useradded is true forward to login
    }
}

}

Advertisement

Answer

You can use a query similar to the following to post a record, then get the ID.

 string sQuery = @"INSERT INTO [ExpenseType]
                                      (
                                         [ExpenseTypeName]
                                        ,[Deleted]
                                        ,[IsTaxable]
                                        ,[UpdatedDate]
                                        ,[UpdatedUser]
                                        ,[ParentCategoryComponentID]
                                        ,[CategoryComponentID]
                                        ,[NLNominalAccountID]
                                        ,[SYSTaxCodeID]
                                      )
                                      VALUES
                                      (
                                         @ExpenseTypeName
                                        ,@Deleted
                                        ,@IsTaxable
                                        ,@UpdatedDate
                                        ,@UpdatedUser
                                        ,@ParentCategoryComponentID
                                        ,@CategoryComponentID
                                        ,@NLNominalAccountID
                                        ,@SYSTaxCodeID
                                      )
                                      SELECT SCOPE_IDENTITY() AS 'ID' ";

                    using ( SqlCommand oSqlCommand = new SqlCommand( sQuery ) )
                    {
                        oSqlCommand.Parameters.AddWithValue( "@ExpenseTypeName", this.ExpenseTypeName );
                        oSqlCommand.Parameters.AddWithValue( "@Deleted", this.Deleted );
                        oSqlCommand.Parameters.AddWithValue( "@IsTaxable", this.IsTaxable );
                        oSqlCommand.Parameters.AddWithValue( "@UpdatedDate", base.GetUpdatedDate() );
                        oSqlCommand.Parameters.AddWithValue( "@UpdatedUser", base.GetUpdatedUser() );
                        oSqlCommand.Parameters.AddWithValue( "@ParentCategoryComponentID", this.ParentCategoryComponentID );
                        oSqlCommand.Parameters.AddWithValue( "@CategoryComponentID", this.CategoryComponentID );
                        oSqlCommand.Parameters.AddWithValue( "@NLNominalAccountID", this.NLNominalAccountID );
                        oSqlCommand.Parameters.AddWithValue( "@SYSTaxCodeID", this.SYSTaxCodeID );

                        using ( DataTable dt = DataTier.ExecuteQuery( oSqlCommand ) )
                        {
                            if ( dt.Rows.Count == 1 )
                            {
                                //Read the new ID from the record that has just been inserted
                                                                string RecordID =  dt.Rows[ 0 ][ "ID" ].ToString();
                            }
                        }
                    }

Note the SELECT SCOPE_IDENTITY() AS ‘ID’ at the end of the query.

and

          if ( dt.Rows.Count == 1 )
                        {
                            //Read the new ID from the record that has just been inserted
                            string RecordID =  dt.Rows[ 0 ][ "ID" ].ToString();
                        }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement