如何在数据库中保存文本框?

时间:2013-10-26 08:13:11

标签: c# asp.net sql

我使用了一些文本框来从用户那里获取一些信息+ sqldatasource

<table class="style1"  >
   <tr>
      <td class="style3" colspan="3" 
           style="font-size: medium; font-family: 'B Nazanin';
           font-weight: bold position: relative; right: 170px" >
           &nbsp; تغییر اطلاعات شخصی
      </td>
   </tr>
   <tr>
      <td class="style3">
         &nbsp;&nbsp;&nbsp;
         <asp:Label ID="Label1" runat="server" Text="  نام: " Font-Bold="True"
              Font-Names="B Nazanin" Font-Size="Medium"></asp:Label>
      </td>
      <td class="style2">
         <asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
      </td>
      <td class="style4">
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                 Display="Dynamic" ErrorMessage="وارد کردن نام الزامی است"
                 ControlToValidate="FirstName">*</asp:RequiredFieldValidator>
      </td>
   </tr>
   <tr>
      <td class="style3">
          &nbsp;&nbsp;&nbsp;
          <asp:Label ID="Label2" runat="server" Text=" نام خانوادگی: "
               Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium">
          </asp:Label>
      </td>
      <td class="style2">
         <asp:TextBox ID="LastName" runat="server"></asp:TextBox>
      </td>
      <td class="style4">
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
             Display="Dynamic" ErrorMessage="وارد کردن نام خانوادگی الزامی است"
             ControlToValidate="LastName">*</asp:RequiredFieldValidator>
      </td>
   </tr>
   <tr>
      <td class="style3">
          &nbsp;&nbsp;&nbsp;
          <asp:Label ID="Label3" runat="server" Text=" شماره دانشجویی : "
               Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium">
         </asp:Label>
      </td>
      <td class="style2">
         <asp:TextBox ID="StudentNumber" runat="server"></asp:TextBox>
      </td>
      <td class="style4">
         <asp:RequiredFieldValidator ID="RequiredFieldValidator3" 
              runat="server" Display="Dynamic" 
              ControlToValidate="StudentNumber"
              ErrorMessage="وارد کردن شماره دانشجویی الزامی است">*
         </asp:RequiredFieldValidator>
      </td>
   </tr>
   <tr>
      <td class="style3">
         &nbsp;&nbsp;
         <asp:Label ID="Label4" runat="server" Text="  تاریخ تولد : "
              Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium">
         </asp:Label>
      </td>
      <td class="style2">
         <asp:TextBox ID="DateOfBirth" runat="server"></asp:TextBox>
      </td>
      <td class="style4">
         <asp:CompareValidator ID="CompareValidator1" runat="server" 
              Display="Dynamic" Operator="DataTypeCheck" 
              ErrorMessage="تاریخ تولد معتبری را وارد نمایید"
              Type="Date" ControlToValidate="dateOfBirth">
         </asp:CompareValidator>
      </td>
   </tr>
   <tr>
      <td class="style3">&nbsp;</td>
      <td class="style2">
         <asp:Button ID="SaveButton" runat="server" Text=" ذخیره تغییرات" 
              Width="102px" style="margin-right: 15px; height: 26px;"  />
      </td>
      <td class="style4">
         <asp:SqlDataSource ID="SqlDataSource1" runat="server"
              ConnectionString=
                   "<%$ ConnectionStrings:ASPNETDBConnectionString1 %>"
              SelectCommand="SELECT aspnet_personalInformation.FirstName,
                    aspnet_personalInformation.LastName,
                    aspnet_personalInformation.StudentNumber,
                    aspnet_personalInformation.DateOfBirth
                 FROM aspnet_personalInformation
                 INNER JOIN aspnet_Users 
                 ON aspnet_personalInformation.UserId = aspnet_Users.UserId
                 WHERE aspnet_personalInformation.UserId=aspnet_Users.UserId
                 ORDER BY aspnet_personalInformation.LastName"
             InsertCommand="INSERT INTO aspnet_PersonalInformation(UserId)
                 SELECT UserId FROM aspnet_Profile">
         </asp:SqlDataSource>
      </td>
   </tr>
</table>

我想在数据库的aspnet_personalinformation表中保存firstname studentname和dateofbirth,但在此之前,我通过插入带有aspnet_profile.userid的sql命令填充一列名为UserId的aspnet_personalinformation表

现在通过运行此代码我的表仍然空白

protected void SaveButton_Click(object sender, EventArgs e)
{
    string str = 
         "Data Source =  .\\SQLEXPRESS;AttachDbFilename=|DataDirectory| 
              \\ASPNETDB.MDF;Integrated Security=True;User Instance=True";
          SqlConnection con = new SqlConnection(str);
    con.Open();
    string query = 
         "INSERT INTO aspnet_PersonalInformation( FirstName,
              LastName,StudentNumber,DateOfBirth)
          VALUES ('" + this.FirstName.Text + "','" + this.LastName.Text + "','" 
             + this.StudentNumber.Text + "','" + this.DateOfBirth.Text + "')    
          WHERE aspnet_PersonalInformation.UserId=aspnet_Profile.UserID";
    SqlCommand cmd=new SqlCommand(query,con);
    cmd.ExecuteNonQuery();
    con.Close();
 }

但它不起作用

4 个答案:

答案 0 :(得分:1)

我认为您要使用update语句,而不是insert

由于您的表最初是通过INSERT INTO aspnet_PersonalInformation(UserId) SELECT UserId FROM aspnet_Profile填充的,因此对于特定的aspnet_PersonalInformation,您将更新 UserId

您的query应更改为:

    string query = 
"UPDATE aspnet_PersonalInformation Set FirstName='" + this.FirstName.Text 
+ "', LastName = '" + this.LastName.Text 
+ "', StudentNumber='" + this.StudentNumber.Text 
+ "', DateOfBirth='" + this.DateOfBirth.Text 
+ "' where aspnet_PersonalInformation.UserId = '" + <ID provided by form> + "'";

你应该为where子句传递一个变量标识符,用实际的用户ID值替换<ID provided by form>

它可能还有很多。如果用户记录尚不存在,那么您需要insert,但不要在where语句中添加insert子句。

此外,您可能希望研究使用绑定变量(AKA参数化查询),而不是通过直接从用户输入中提取来连接大型SQL字符串。您当前的查询可能容易受到SQL注入的影响,具体取决于表单数据的处理方式(例如,如果没有按摩以删除脚标记的单引号,则用户可以通过在单个引号中输入单引号来中断SQL表格字段。)

使用绑定变量有点清晰,即:

protected void SaveButton_Click(object sender, EventArgs e)
{
    string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ASPNETDB.MDF;Integrated Security=True;User Instance=True";
    try
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            con.Open();

            string query = 
            "UPDATE aspnet_PersonalInformation Set FirstName=@firstName, LastName=@lastName, StudentNumber=@studentNo, DateOfBirth=@dob where UserId = @userId";

            SqlCommand cmd=new SqlCommand(query,con); 

            string userId = "Bob"; // should be an actual user ID, from form

            cmd.Parameters.AddWithValue("@firstName", FirstName.Text);
            cmd.Parameters.AddWithValue("@lastName", LastName.Text);
            cmd.Parameters.AddWithValue("@studentNo", StudentNumber.Text);
            cmd.Parameters.AddWithValue("@dob", DateOfBirth.Text);
            cmd.Parameters.AddWithValue("@userId", userId);

            Int32 rowsAffected = command.ExecuteNonQuery();
        }
    }
    catch (Exception ex)
    {
       // examine ex.Message to figure out what went wrong
    }
}

答案 1 :(得分:0)

删除其中条件

query = "INSERT INTO aspnet_PersonalInformation( FirstName, LastName,StudentNumber,DateOfBirth) VALUES ('" + this.FirstName.Text + "','" + this.LastName.Text + "','" + this.StudentNumber.Text + "','" + this.DateOfBirth.Text + "')";

答案 2 :(得分:0)

您还需要将userID插入表aspnet_PersonalInformation。像这样

INSERT INTO aspnet_PersonalInformation( FirstName, LastName,StudentNumber,DateOfBirth,UserID) VALUES ('" + this.FirstName.Text + "','" + this.LastName.Text + "','" + this.StudentNumber.Text + "','" + this.DateOfBirth.Text + "','" + aspnet_Profile.UserID + "')

答案 3 :(得分:0)

此查询:

string query = 
         "INSERT INTO aspnet_PersonalInformation( FirstName,
              LastName,StudentNumber,DateOfBirth)
          VALUES ('" + this.FirstName.Text + "','" + this.LastName.Text + "','" 
             + this.StudentNumber.Text + "','" + this.DateOfBirth.Text + "')    
          WHERE aspnet_PersonalInformation.UserId=aspnet_Profile.UserID";

不起作用,因为aspnet_Profile是数据库中的另一个表。你不能这样做是因为:

  1. 在INSERT语句中无法使用相对条件设置WHERE语句;
  2. 即使有可能,也必须指定你在两个表之间进行连接;
  3. 因为您只需要保存用户记录,所以您应该:

    1. 将您的UserID保存在变量和aspnet_Profile表中,如前所述;

    2. 使用如下查询插入相关记录:

    3. 
      string userID = "A333D2FC-B4F1-420F-872B-7C872E82AD12"; /* your userId is stored in this variable */ 
      
      string query = "INSERT INTO aspnet_PersonalInformation(UserID, FirstName, LastName, StudentNumber,DateOfBirth) " + "VALUES ('" + userID + "',' " + this.FirstName.Text + "','" + this.LastName.Text + "','" + this.StudentNumber.Text + "','" + this.DateOfBirth.Text + "') ";