2016-03-04 74 views
0

我從來沒有這樣做過,所以我希望你們中的一些人知道如何去做。從插入抓取會話 - C#和MySQL

本質上,我在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> 
+0

你使用MySql作爲數據庫還是Sql Server?代碼使用Sql Server的類,但你的標籤說MySql。要檢索最後的身份值,答案會不同 – Steve

+0

我相信它的MySql – Marty

回答

0

你的代碼是醜陋的,越野車,並要求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山口設置爲AUTO_INCREMENT

編輯。 在SQL Server中將其更改爲SCOPE_IDENTITY()

+0

謝謝奧斯卡,這個新東西,所以這樣顯示。你能解釋一下int result =(int)myCommand.ExecuteScalar();位?我的頌歌在哪裏?我怎樣才能在下一頁獲得?是不是像「」 – Marty

0

首先,您應該知道字符串串聯在數據庫代碼中是非常糟糕的做法。它導致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 vs Sql Server問題。我會告訴你同樣的代碼,但LAST_INSERT_ID功能用於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; 

注意使用和類的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>"); 
+1

SCOPE_IDENTITY()是SQL Server特有的,他要求MySql數據庫 – Oscar

+0

@Oscar標籤是mysql,但他使用SqlCommand。需要在這裏澄清 – Steve

+0

我相信它的MySQL – Marty

0

你要附加給你的SQL字符串的結尾:

SELECT SCOPE_IDENTITY() 

這將返回新創建的記錄的ID。

int id = myCommand.ExecuteScalar(); 

然後,您可以使用Response.Redirect的用id去你的下一個頁面,並用它來從你的新加載任何東西:然後,您可以通過替換您myCommand.ExecuteQuery()得到該值創造了記錄。