【问题标题】:Grab session from insert - C# and MySQL从插入中获取会话 - C# 和 MySQL
【发布时间】:2016-03-04 13:52:15
【问题描述】:

我以前从未这样做过,所以我希望你们中的一些人知道如何去做。

基本上我在 CreateModule 页面上进行了插入,然后我想获取新的 ModuleID(它是在数据库中创建的,我没有插入)和 ModuleTitle 并将其带到 CreateModule2 页面。

我非常感谢所有的帮助。

C#

protected void CreateNewModule_Click(object sender, EventArgs e)
        {
            // open new connection
            SqlConnection connect1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            connect1.Open();

            // initalise variables for update
            String Title = ModuleTitleText.Text;
            String Mtext = ModuleTextText.Text;
            String Com = CompulsoryDropdown.Text;
            String CAT = CATpointsText.Text;
            String Lev = LevelText.Text;
            String Ass = AssessmentText.Text;
            String MCode = ModuleCodeText.Text;
            String Status = ModuleStatusDropdown.Text;

            // convert string to Int
            Int32 Levconverted = Convert.ToInt32(Lev);
            Int32 CATconverted = Convert.ToInt32(CAT);
            

            // Insert Query to Add new student record to student records table in database
            String queryInsert = "INSERT INTO Module_Info (ModuleTitle, ModuleText, Compulsory, CATpoints, Level, Assessment, ModuleCode, ModuleStatus) VALUES ('" + Title + "', '" + Mtext + "', '" + Com + "', '" + CAT + "', '" + Lev + "', '" + Ass + "',  '" + MCode + "', '" + Status + "'); SELECT  LAST_INSERT_ID()";

            // excute insert query
            SqlCommand myCommand = new SqlCommand(queryInsert, connect1);
            myCommand.Parameters.Add("@title", SqlDbType.NVarChar).Value = Title;
            int idmodule = Convert.ToInt32(myCommand.ExecuteScalar());
            
            

            // alerts for successfull upload
            Response.Write("<script type='text/javascript'>");
            Response.Write("alert('New Module has been added. Please select a course to align the module to in the next page.');");
            Response.Write("document.location.href='CreateModule2.aspx';");
            Response.Write("</script>");
        }

然后这是前端代码。

<table style="width: 100%;">
                <tr>
                    <td><asp:Label ID="ModuleTitle" runat="server" Text="Module Title" Font-Bold="true"></asp:Label></td>
                    <td><asp:TextBox ID="ModuleTitleText" runat="server" TextMode="MultiLine" style="overflow:hidden" onkeyup="AutoExpand(this)" Rows="1" width="700px" ></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" id="reqModuleTitle" controltovalidate="ModuleTitleText" 
                            errormessage="* Please enter the module title" ForeColor="Red" Font-Bold="true" Font-Size="Small" /></td>
                </tr>
                <tr>
                    <td><asp:Label ID="ModuleText" runat="server" Text="Module Text" Font-Bold="true" ></asp:Label></td>
                    <td><asp:TextBox ID="ModuleTextText" runat="server" TextMode="MultiLine" style="overflow:hidden" onkeyup="AutoExpand(this)" Rows="4" width="800px"></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" id="reqModuleText" controltovalidate="ModuleTextText" 
                            errormessage="*Please enter the Module Information" ForeColor="Red" Font-Bold="true" Font-Size="Small" /></td>
                </tr>
                <tr>
               <!-- dropdown list to select value-->
                  <td><asp:Label ID="Compulsory" runat="server" Text="Compulsory Status" Font-Bold="true" ></asp:Label> </td>
                    <td><asp:DropDownList ID="CompulsoryDropdown" runat="server">
                        <asp:ListItem Value="true">Compulsory</asp:ListItem>
                        <asp:ListItem Value="false">Non-Compulsory</asp:ListItem>
                </asp:DropDownList></td>
                </tr>
                <tr>
                    <td><asp:Label ID="CATpoints" runat="server" Text="CATpoints" Font-Bold="true"></asp:Label></td>
                    <td><asp:TextBox ID="CATpointsText" runat="server" TextMode="MultiLine" style="overflow:hidden" onkeyup="AutoExpand(this)" Rows="1" width="100px"></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" id="reqCATpoints" controltovalidate="CATpointsText" 
                            errormessage="*Please enter the A-Level Requirements" ForeColor="Red" Font-Bold="true" Font-Size="Small" /></td>
                </tr>
                <tr>
                    <td><asp:Label ID="Level" runat="server" Text="Level" Font-Bold="true"></asp:Label></td>
                    <td><asp:TextBox ID="LevelText" runat="server" TextMode="MultiLine" style="overflow:hidden" onkeyup="AutoExpand(this)" Rows="1" width="100px"></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" id="reqLevel" controltovalidate="LevelText" 
                            errormessage="*Please enter the Level of the module" ForeColor="Red" Font-Bold="true" Font-Size="Small" /></td>
                </tr>
                <tr>
                    <td><asp:Label ID="Assessment" runat="server" Text="Assessment" Font-Bold="true"></asp:Label></td>
                    <td><asp:TextBox ID="AssessmentText" runat="server" TextMode="MultiLine" style="overflow:hidden" onkeyup="AutoExpand(this)" Rows="1" width="600px"></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" id="ReqAssessment" controltovalidate="AssessmentText" 
                            errormessage="*Please enter the Assessment details" ForeColor="Red" Font-Bold="true" Font-Size="Small" /></td>
                </tr>
                <tr>
                    <td><asp:Label ID="ModuleCode" runat="server" Text="Module Code" Font-Bold="true" ></asp:Label>  </td>
                    <td><asp:TextBox ID="ModuleCodeText" runat="server"  TextMode="MultiLine" style="overflow:hidden" onkeyup="AutoExpand(this)" Rows="1" width="300px"></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" id="ReqModuleCode" controltovalidate="ModuleCodeText" 
                            errormessage="*Please enter the module code" ForeColor="Red" Font-Bold="true" Font-Size="Small" />
                    </td>
                </tr>
                <tr>
               <!-- dropdown list to select value-->
                  <td><asp:Label ID="ModuleStatus" runat="server" Text="Module Status" Font-Bold="true" ></asp:Label> </td>
                    <td><asp:DropDownList ID="ModuleStatusDropdown" runat="server">
                        <asp:ListItem Value="Running">Running</asp:ListItem>
                        <asp:ListItem Value="Suspended">Suspended</asp:ListItem>
                        <asp:ListItem Value="Withdrawn">Withdrawn</asp:ListItem>
                </asp:DropDownList></td>
            </tr>
               <tr>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
               </tr>
               <tr>
                    <td><asp:Button ID="SubmitModule" runat="server" Text="Submit" OnClick="CreateNewModule_Click" /></td>
               </tr>
            </table>

【问题讨论】:

  • 您是使用 MySql 作为数据库还是 Sql Server ?代码使用 Sql Server 的类,但您的标签显示 MySql。要检索最后一个身份值,答案会有所不同

标签: c# mysql visual-studio session sql-insert


【解决方案1】:

您需要将此附加到 SQL 字符串的末尾:

SELECT SCOPE_IDENTITY()

这将返回新创建记录的 ID。然后,您可以通过将 myCommand.ExecuteQuery() 替换为:

int id = myCommand.ExecuteScalar();

然后,您可以使用带有 id 的 Response.Redirect 进入下一页,并使用它从新创建的记录中加载任何内容。

【讨论】:

    【解决方案2】:

    您的代码很丑陋、有缺陷,并且要求进行 SQL 注入。只是祈祷没有人输入像'DROP TABLE'Module_Info'这样的文本;在 ModuleTitleText.. 也就是说,将您的查询更改为:

    String queryInsert = "INSERT INTO Module_Info (ModuleTitle, ModuleText, Compulsory, CATpoints, Level, Assessment, ModuleCode, ModuleStatus) VALUES ('" + Title + "', '" + Mtext + "', '" + Com + "', '" + CAT + "', '" + Lev + "', '" + Ass + "',  '" + MCode + "', '" + Status + "'); SELECT  LAST_INSERT_ID()"
    

    然后使用:

    int result = (int) myCommand.ExecuteScalar();
    

    假设你的 id col 设置为 AUTO_INCREMENT

    编辑。 在 SQL Server 中将其更改为 SCOPE_IDENTITY()

    【讨论】:

    • 感谢 Oscar,对这些东西不熟悉,所以以这种方式展示。你能解释一下 int result = (int) myCommand.ExecuteScalar();少量?我把它放在我的颂歌的什么地方?我如何在下一页中得到它?是不是像“
    【解决方案3】:

    首先您应该知道字符串连接在数据库代码中是一种非常糟糕的做法。它会导致Sql Injections 和解析问题。对于所有这些原因,更好的做法是使用参数化查询,然后取回表中最后插入的标识,修复非常简单

    String queryInsert = @"INSERT INTO Module_Info 
            (ModuleTitle, ModuleText, Compulsory, CATpoints, Level, 
             Assessment, ModuleCode, ModuleStatus) VALUES 
            (@title, @mtext, @Com, @cat, @lev, @Ass, @MCode, @Status);
            SELECT SCOPE_IDENTITY()";
    
    SqlCommand myCommand = new SqlCommand(queryInsert, connect1);
    myCommand.Parameters.Add("@title", SqlDbType.NVarChar).Value = Title;
    .... ...
    // and so on with all other parameters required
    // paying attention to use the appropriate SqlDbType for the 
    // field updated by the parameter value...
    
    // Don't run ExecuteNonQuery, but ExecuteScalar to get the last
    // value returned by SCOPE_IDENTITY()
    int idmodule = Convert.ToInt32(myCommand.ExecuteScalar());
    

    如您所见,查询包含两条指令,最后一条返回插入到 module_info 表中的 ID,您可以使用 ExecuteScalar 获取它

    等待有关 MySql 与 Sql Server 问题的澄清。我将向您展示相同的代码,但用于 MySql

    String queryInsert = @"INSERT INTO Module_Info 
            (ModuleTitle, ModuleText, Compulsory, CATpoints, Level, 
             Assessment, ModuleCode, ModuleStatus) VALUES 
            (@title, @mtext, @Com, @cat, @lev, @Ass, @MCode, @Status);
            SELECT last_insert_id()";
    
    MySqlCommand myCommand = new MySqlCommand(queryInsert, connect1);
    myCommand.Parameters.Add("@title", MySqlDbType.VarChar).Value = Title;
    

    注意 last_insert_id 函数的使用,以及 MySql 的类而不是 Sql Server 的使用

    关于将其传递给您的调用页面。通常的方法是将结果放入查询字符串中,然后在调用的页面中查看 QueryString 集合来获取它

        Response.Write("<script type='text/javascript'>");
        Response.Write("alert('New Module has been added. Please select a course to align the module to in the next page.');");
        Response.Write("document.location.href='CreateModule2.aspx?ModuleID=" + idmodule + "&Title=" + Title + "';");
        Response.Write("</script>");
    

    【讨论】:

    • SCOPE_IDENTITY() 是 SQL Server 特定的,他要求 MySql 数据库
    • @Oscar 标签是 mysql,但他使用 SqlCommand。这里需要澄清一下
    • 我将在问题中编辑我的代码,您可以告诉我我是否正确完成了
    • 否 @Marty 不要更改原始问题,否则我们会失去对情况的跟踪。尝试使用您自己的代码,如果您有其他问题,请再次询问或发布新问题
    • @Marty 您的更新不会添加所有必需的参数(每个值一个)请参阅上面第一个 sn-p 中的示例和 cmets。
    猜你喜欢
    • 2011-09-09
    • 2014-04-18
    • 1970-01-01
    • 2019-03-25
    • 2021-09-12
    • 2019-11-07
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    相关资源
    最近更新 更多