【问题标题】:How to convert last insert id into string?如何将最后一个插入ID转换为字符串?
【发布时间】:2011-07-29 07:25:29
【问题描述】:

我有一个创建帐户页面,在该页面上我有一个按钮可以将所有详细信息插入两个单独的表中,其中一个表图片依赖于通过 UserID 的用户表 1:1 关系。

我已经编写了一些代码来尝试获取最后一个插入 id,以便我可以插入到图片表中:

    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
        }
    }
}

不确定这是否正确,我还需要知道如何将 select 语句转换为字符串,以便我可以从 User 表中检索 UserID,请参阅数据库结构:

编辑

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
    }
}

}

【问题讨论】:

    标签: c# asp.net mysql sql html


    【解决方案1】:

    您可以使用类似于以下的查询来发布记录,然后获取 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();
                                }
                            }
                        }
    

    注意查询末尾的 SELECT SCOPE_IDENTITY() AS 'ID'。

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

    【讨论】:

    • SCOPE_IDENTITY 的工作方式是否与 Select last_insert_id 相同?
    • 我需要最后插入的用户 ID,以便将其传递给插入图片
    • SCOPE_IDENTITY() 返回插入到同一范围内的标识列中的最后一个标识值。范围是一个模块:存储过程、触发器、函数或批处理。因此,如果两条语句在同一个存储过程、函数或批处理中,则它们属于同一范围。我以前没有听说过 Select Last Insert ID。是你的方法吗?
    • 好的,首先在单个查询中插入您的用户记录,存储从查询返回的 UserID 并在触发下一个查询时使用它来插入图片记录
    • SELECT LAST_INSERT_ID() 是 mysql 语法
    猜你喜欢
    • 2010-12-20
    • 1970-01-01
    • 2020-11-05
    • 2012-05-30
    • 2016-02-16
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    相关资源
    最近更新 更多