【问题标题】:how to save textbox in database?如何将文本框保存在数据库中?
【发布时间】:2013-10-26 23:15:34
【问题描述】:

我使用一些文本框从用户那里获取一些信息 + 一个 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 lastname studentnumber 和 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();
 }

但它不起作用

【问题讨论】:

  • 什么不起作用?你有错误吗?

标签: c# asp.net sql


【解决方案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 子句传递一个变量标识符,以将 &lt;ID provided by form&gt; 替换为实际的用户 ID 值。

它可能比这更多。如果用户记录还不存在,那么您将需要insert 它,但不要在您的insert 语句中添加where 子句。

此外,您可能希望考虑使用绑定变量(AKA 参数化查询),而不是通过直接从用户输入中提取来连接大 SQL 字符串。您当前的查询可能容易受到 SQL 注入的攻击,具体取决于表单数据的处理方式(例如,如果未对其进行按摩以删除单引号 AKA 脚标记,则用户可以通过在其中一个中输入单引号来破坏 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
    }
}

【讨论】:

    【解决方案2】:

    移除where条件

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

    【讨论】:

      【解决方案3】:

      您还需要将用户 ID 插入表 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 + "')
      

      【讨论】:

      • 我想这样做,但它无法识别“aspnet_Profile.UserID”
      • 错误表明当前上下文中不存在名称aspnet_Profile。
      • @mahsoon,在连接字符串的末尾添加;Initial Catalog=aspnetdb
      【解决方案4】:

      这个查询:

      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. 即使有可能,您也必须指定要在两个表之间进行连接;

      因为你只需要保存你的用户记录,那么你应该:

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

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

      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 + "') ";

      【讨论】:

        猜你喜欢
        • 2012-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-12
        • 2013-09-01
        • 1970-01-01
        • 2014-05-26
        相关资源
        最近更新 更多