如何将列表添加到 SQL 数据库(使用 java)

问题描述:

我是 sql 的新手,我想知道如何将列表添加到数据库中.这是我的意思:

I am new to sql and I was wondering how i can add a list to a database. Here is what I mean:

我有一个这样的java类,我想将其信息插入到数据库中:

I have an a java class like this that i want to insert its info into a db:

public class Dog{

  private int dog_id;
  private String dog_name;
  private ArrayList<String> dog_friends;

}

每个狗对象都有不同数量的朋友.我的问题是如何将此列表添加到数据库中.我计划有 3 列(id、name、list),我只是不知道如何添加列表.

Every dog object will have a different amount size of friends. My question is how i can add this list to the db. I was planning on having 3 columns (id,name,list), I just dont know how to add a list.

你所拥有的是,在关系数据库世界中,称为一对多关系,它需要两个数据库表来表示信息.

What you have is, in the relational database world, called a one-to-many relationship, and it requires two database tables to represent the information.

在您的第一个表中,您将拥有 idname;在您的第二个表中,您将拥有 dog_idfriend_iddog_friend.

In your first table, you'll have id and name; in your second table you'll have dog_id, friend_id and dog_friend.

对于第一个表中的每个条目,第二个表中可能有很多条目.当您在第二个表中插入一行时,请确保将 dog_id 设置为与第一个表中的 id 匹配.

There will be possibly many entries in the second table for every entry in the first table. When you insert a row in the second table, be sure to set dog_id to match the id in the first table.

通过这种结构,您可以在 SQL 查询中使用 JOIN 来一次性获取所有信息,也可以根据需要独立查询表.

With this structure, you can use JOINs in your SQL query to get all the information at once, or query the tables independently, depending on your needs.