【问题标题】:Insert a record with a value partly from another table插入具有部分来自另一个表的值的记录
【发布时间】:2011-02-15 02:48:12
【问题描述】:

我有两张桌子,ProteinsSpeciesProtein 具有 Species.Id 作为外键约束。当我插入数据时,我知道蛋白质所属物种的名称,但不知道Id。所以我做了以下事情:

    PreparedStatement query = connection.prepareStatement(
        "SELECT Id FROM Species WHERE ShortName = ?");
    query.setString(1, protein.getSpecies().getShortName());
    ResultSet result = query.executeQuery();
    if (result.next()) {
        PreparedStatement statement = connection.prepareStatement(
        "INSERT INTO Proteins(SpeciesId, UniProtKBAccessionNumber) VALUES (?, ?)");

        statement.setString(1, result.getString(1));
        statement.setString(2, protein.getUniProtKBAccessionNumber().toString());

        statement.execute();
    }
    else
        throw new IllegalArgumentException("The species of this protein is not recognized!");

基本上,我得到与名称对应的Id,然后插入蛋白质。这在很多方面看起来都非常笨拙。有没有更优雅的方法来实现这一点?我正在开发一个 SQLite 数据库。

【问题讨论】:

    标签: sqlite select jdbc insert foreign-keys


    【解决方案1】:

    试试这个

    INSERT INTO Proteins(SpeciesId, UniProtKBAccessionNumber) VALUES ((SELECT Id FROM Species WHERE ShortName = ?), ?)
    

    然后使用 Shortname 和 UniProtKBAccessionNumber 作为参数

    【讨论】:

    • 如果我有 10 列,我想用一个不同的列值复制这一行 - 这是我的主键。我必须为 9 列写一个选择...有更好的方法吗?
    猜你喜欢
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2018-05-24
    • 2016-06-20
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多