【问题标题】:Getting the value of the primary key of the first table into the foreign key of the second table using two forms使用两种形式将第一个表的主键的值获取到第二个表的外键中
【发布时间】:2020-01-22 06:05:43
【问题描述】:

我已经创建了一个 JSP 页面来注册新用户。在注册表格中,有 5 个字段供用户输入他们的详细信息。

按下提交按钮后,他们将被带到另一个页面,在那里他们必须填写另一个表格,其中包含他们的一些其他详细信息。用户在第一个表单中输入的数据已成功插入到第一个表中,但是,当他们以第二个表单发送数据时,会出现错误提示

"java.sql.SQLException: 字段 'artist_id' 没有默认值 价值”。

这里atrist_id 是第一个表的主键,它是第二个表的外键。以下是注册和artist_info

structures of the first table

structures of the second table

try {

    String address_1 = request.getParameter("address_1");
    String address_2 = request.getParameter("address_2");
    String city = request.getParameter("city");
    String postal_code = request.getParameter("postal_code");
    String phone_number = request.getParameter("phone_number");

    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/painter?autoReconnect=true&useSSL=false", "root", "");
    Statement st = con.createStatement();

    //st.executeUpdate("insert into signup(uid,fname,lname,email,password,country)values('"+firstName+"','"+lastName+"','"+email+"','"+password+"','"+country+"')");
    st.executeUpdate("insert into artist_info(address_1,address_2,city,postal_code,phone_number)"
        + "values('" + address_1 + "','" + address_2 + "','" + city + "','" + postal_code + "','" + phone_number + "')");

我应该如何更改此代码以将artist_id 的值放入第二个表的外键(artist_id)中。谢谢。

【问题讨论】:

  • 两张图片是一样的。我猜虽然那个artist_id 在注册表中?通常要在两个表中进行插入,您首先必须提交一个,然后获取它的 id,然后提交新的。要么这样,要么您将外键设为非空,这样您就可以在提交后将其设置为正确的值。
  • 我放了正确的图像。请再次检查:)

标签: sql jsp jakarta-ee primary-key database-connectivity


【解决方案1】:

我猜这是因为如果您将表中的字段设置为主键,则它不能为空。似乎您没有序列生成器,因此您必须在尝试提交之前在 artist_info 中设置 Artist_id。

所以,这里的解决方案是:

  1. 在您的数据库中为该字段获取序列生成器
  2. 不要忘记在artist_info 中设置artist_id。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 2015-09-18
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多