简体   繁体   English

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

[英]how to save textbox in database?

I used some textboxes to get some info from users + a sqldatasource 我使用一些文本框从用户+ 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>

I wanna save firstname lastname studentnumber and dateofbirth in aspnet_personalinformation table in database but before that, i fill one column of aspnet_personalinformation table named UserId by inserting sql command with aspnet_profile.userid 我想在数据库的aspnet_personalinformation表中保存名字,姓氏,学生编号和出生日期,但在此之前,我通过使用aspnet_profile.userid插入sql命令来填充名为UserId的aspnet_personalinformation表的一列

now by running this code my table has still blanks 现在通过运行此代码,我的表仍然空白

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();
 }

but it doesn't work 但这不起作用

I think you want to use an update statement, not insert . 我认为您想使用update语句,而不是insert

Since your table was initially populated via INSERT INTO aspnet_PersonalInformation(UserId) SELECT UserId FROM aspnet_Profile you will be updating aspnet_PersonalInformation for a specific UserId . 由于您的表最初是通过INSERT INTO aspnet_PersonalInformation(UserId) SELECT UserId FROM aspnet_Profile填充的INSERT INTO aspnet_PersonalInformation(UserId) SELECT UserId FROM aspnet_Profile您将为特定的UserId 更新 aspnet_PersonalInformation

Your query should be changed to: 您的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> + "'";

And you should pass a variable identifier for the where clause to replace <ID provided by form> with an actual user ID value. 而且,您应该为where子句传递一个变量标识符,以用实际的用户ID值替换<ID provided by form>

There's likely a lot more to it than this. 可能还有更多的东西。 If the user record does not exist yet, then you will want to insert it, but do not put a where clause in your insert statement. 如果用户记录尚不存在,则将要insert该记录,但不要在insert语句中放置where子句。

Also, you may want to look into using bind variables (AKA parameterized queries) instead of concatenating a big SQL string by pulling directly from user input. 另外,您可能希望研究使用绑定变量(AKA参数化查询),而不是通过直接从用户输入中提取来连接大的SQL字符串。 Your current query may be vulnerable to SQL injection depending on how the form data is processed (if it is not massaged to remove single quotes AKA the foot marker, for example, then a user can break the SQL by entering a single quote into one of the form fields.) 您当前的查询可能容易受到SQL注入的影响,具体取决于处理表单数据的方式(例如,如果未对其进行处理以删除单引号(也称为“脚”标记),则用户可以通过在其中一个输入单引号来破坏SQL。表单字段。)

Using bind variables is a bit cleaner, to wit: 使用绑定变量更干净一点:

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

删除where条件

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

you need to insert the userID to the table aspnet_PersonalInformation also. 您还需要将用户ID插入表aspnet_PersonalInformation like this 像这样

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

This query: 该查询:

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";

won't work, because aspnet_Profile is another table in your database. 将不起作用,因为aspnet_Profile是数据库中的另一个表。 You cannot do this because: 您不能这样做,因为:

  1. It's not possible to set a WHERE statement, with the relative condition, in an INSERT statement; 不能在INSERT语句中设置带有相对条件的WHERE语句。
  2. Even if it would be possible, you have to specify you're doing a join between the two tables; 即使有可能,您也必须指定要在两个表之间进行联接。

Because you only have to save your user record, then you should: 因为只需要保存用户记录,那么您应该:

  1. Save your UserID in a variable and in the aspnet_Profile table, as you previously mentioned; aspnet_Profile ,将您的UserID保存在变量和aspnet_Profile表中;

  2. Insert the related record using a query like this: 使用如下查询插入相关记录:


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数据库中的数据检索到文本框中,以及如何将同一文本框中的编辑数据保存到数据库中 - how to retrieve data from database into textbox and save the edited data from the same textbox to database c#如何插入文本框值并将其保存到sql数据库? - c# How to insert textbox value and save it to sql database? 如何从MVC中动态添加的文本框中保存数据库中的多个数据 - how to save multiple data in database from dynamic added textbox in mvc 如何使用实体框架将日期从文本框保存到数据库? - How can save date from textbox to database using Entity Framework? 如何将多行文本框上的值保存到数据库中或如何将文本文件中不带分隔符的文本保存到数据库中 - How to save to database the value on a multiline textbox or how to save to database a non-delimited text on a textfile 如何将我的文本框内容保存在数据库中? 文本框使用HTML和CSS编程 - How can I save my Textbox content in a database? Textbox is programmed in HTML and CSS 将网格视图文本框数据保存到数据库 - Save Grid View Textbox Data to database 绑定表行文本框和ID,然后保存到数据库 - Binding Table row textbox and Id, Then save to database 如何创建文本框以保存路径 - How to create a Textbox to save a path 如何保存动态文本框的值? - How to save dynamic textbox value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM