Answer the question
In order to leave comments, you need to log in
How to store an ArrayList in MySQL Java?
In the course of work, I encountered the problem of saving several key-values in one cell.
For example, a student has a "groups" column in the database, 5-6 id-keys should be written there. How to write values from ArrayList there in Java? Maybe I'm trying to do it wrong. I do this: I take from the ArrayList from the values \u200b\u200bI make the only String, this is with Insert. And at Read on "," I divide into separate lines. How do you implement this, please tell me? Thanks in advance!
Answer the question
In order to leave comments, you need to log in
You need to create a separate table for groups, which will have 2 columns: student id and group id. Those. the table will have a row for each student group.
If correct, then one field for one object. Usually, several id's are not put into one field. You need 2 tables with fields: student id and group id.
table: student_group
+-------------+-----------+
| student_id | group_id |
+-------------+-----------+
| 1 | 4 |
+-------------+-----------+
| 1 | 5 |
+-------------+-----------+
| 1 | 10 |
+-------------+-----------+
| 1 | 99 |
+-------------+-----------+
| 2 | 8 |
+-------------+-----------+
| 2 | 30 |
+-------------+-----------+
You should read about one-to-one, one-to-many, many-to-many database relationships.
If a student can be in several groups, and there can be different students in the group, then this relationship is called many-to-many. In this case, 3 tables are usually created. 1 - students (students), 2 - groups (groups) and 3 is an auxiliary table of two columns - student id and group id (student_group).
for example, a request to select groups in which a student is a member:
To add links, simply add an entry to table 3, for example:
For multiple addition of groups in jdbc there is a batch insert, like this:
String sql = "insert into student_group (student_id, group_id) values (?, ?)";
Connection connection = new getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
String student_id = "Какойто_ид_студента";
ArrayList<String> groups = // это твой лист с группами
for (Student group : groups) {
ps.setString(1, student_id);
ps.setString(2, group);
ps.addBatch();
}
ps.executeBatch();
ps.close();
connection.close();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question