如何将文本字段中的数据插入到数据库的外键中

w8f9ii69  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(417)

如何将文本字段中的数据插入到数据库的外键中。基本上,我有名为employee和role的表,roleid是employee中的外键,但role文本字段是字符串。我有这个

  1. String Query = "insert into EMPLOYEE (LastName,FirstName,Manager,RoleId,HireStatus) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + this.txtManager.Text + "','" + this.txtRoleId.Text + "','" + this.txtHireStatus.Text + "');";

已编辑-我有这个,但不能用以下字符串选择

  1. string Query = "insert into EMPLOYEE(LastName,FirstName,RoleId,Manager,HireStatus) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + ( SELECT RoleId From Role WHERE Role.RoleId = this.txtRole.Text ) + "','" + this.txtManager.Text + "','" + this.cmbHireStatus.Text + "');";
cld4siwp

cld4siwp1#

我认为你应该这样做:

  1. String Query = "insert into EMPLOYEE (LastName,FirstName,Manager,RoleId,HireStatus) values('" + this.txtLName.Text + "','" + this.txtFName.Text + "','" + this.txtManager.Text + "','" + this.txtRoleId.Text + "','" + this.txtHireStatus.Text + "');";
siv3szwd

siv3szwd2#

如果您试图添加一个新员工分配给一个现有的角色,那么一个更好的设计是有一个 dropdown 填充所有角色而不是 textbox 供用户输入。
下拉列表中应该包含roles表中的所有角色(绘制 SelectedValue 下拉列表的属性为-roleid and SelectedText 到rolename)。
当您提交表单时,您将获得selectedvalue(roleid),您可以将其作为表单的一部分直接发送 INSERT 声明,即。, dropDownRole.SelectedValue 而不是 txtRoleId.Text 注意:您的insert查询似乎是sql注入的典型候选。我建议您将其转换为参数化查询。
更新:现在我知道它是一个winforms应用程序,添加了更详细的代码片段。下面是如何在winforms世界中实现这一点(虽然不如web应用程序世界直观:)。请接受我的意见,我已经多年没有编写winforms代码片段了。
像这样定义你的下拉组合框-

  1. cbxRole.DataSource = roles; // data from back end
  2. cbxRole.Name = "Role";
  3. cbxRole.DropDownStyle = ComboBoxStyle.DropDownList;
  4. cbxRole.DisplayMember = "RoleName"; // should match the property name in your roles data table
  5. cbxRole.ValueMember = "RoleId"; // should match the property name in your roles data table
  6. cbxRole.SelectedItem = null;
  7. cbxRole.SelectedText = "Select Role";

观察 ValueMember 以及 DisplayMember 属性。 DisplayMember 说明角色数据源中用于显示为下拉项文本的属性。 ValueMember 指定用于标识幕后每个项的属性。
提交详细信息时,请访问selectedvalue属性以获取与所选角色名称对应的roleid。

  1. private void btnCreate_Click(object sender, EventArgs e)
  2. {
  3. var firstName = txtFirstName.Text;
  4. var lastName = txtLastName.Text;
  5. var roleId = (int)cbxRole.SelectedValue;
  6. }

这个 SelectedValue 属性获取 ValueMember 属性,即roleid值。现在,您可以将这个“roleid”变量的值发送到insert查询。
以下是提交时的样子-

以下是快速示例用户界面-

展开查看全部

相关问题