More than one value java

[Solved]-more than one value for a column in database-Java

You should create a table «language» with all the different languages you want to use, and then use a foreign key to link to this table from a LanguageID column in your other table.

Edit: If you want more than 1 language for a given record then you will need to also create a linking table which links the record to a given LanguageID. Then you can put any number of different languages in for a given record by creating new records in the linking table.

I think Zack answer is correct, but if you REALLY need to store multiple values in a database row, you can use the VARCHAR type and use a separator like «;» to separate the values, but you must be carefull when adding/editting these values to parse them correctly.

Or if you are using an Oracle Database, you can define the type of the column as an ARRAY, but this is a propietary solution which generates too much dependency, i don’t recomend it.

What you’re talking about is a many-to-many relationship between your table (you didn’t give a name) and the languages.
Let me assume that your table is about people and that you want to track which people are proficient in which languages.
Any given person will have a proficiency in one (perhaps zero) or more languages. To model this, you need three tables: Person, Language and a third one that links the two, perhaps LanguageProficiency which has a reference to one person and one language. In this table, you can have multiple rows for the same person or the same language, but you should have only one entry per unique combination of person and language (i.e. these two columns form the primary key of this table).

Читайте также:  What is data binding in php

The advantage of using a third table here (over some of the other suggestions such as concatenating them into a text field) is that it is easy to expand it to include additional attributes, such as how many years a person has used the language, or a rating for the level of mastery in a language, or some test score. These are things you would want to know for each combination of a person and language, so it belongs in the LanguageProficiency table.

Do you mean an enumeration, where only certain values can be used, or do you mean storing more than one value in a column for a given row?

Enumeration

-- Works in MySQL for sure table whatever ( language enum('JAVA','C++,'C#') NOT NULL DEFAULT 'JAVA' >; 

Multiple Values

Do not do this, use a many-to-many relationship instead:

table whatever ( id int ); table language ( id int, name varchar(256) ) table whatever_language)( whatever_id int, language_id int ) -- don't forget foreign key constraints 

You need to create a Language table as mentioned by Zack where each language is represented then have a table to link them to such as _-Langage (where _ is replaced with original table name)

This linking table will have an incremental index as its Primary key and will have a Foreign Key of the Language table and the Original table. Then there can be multiple rows in the linking table for each language needed in the original table

Josh Mein 27382

If you know about database design and want to get rid of this additional language table which is the usual «good» way to do it you can use for example a string.

In the string keep the ISO language code which is somethink like «en-en» (first country, second language variant») together with a separator token, obviously space might be a good one so that «en-en de-de » for english and german.

You can then use the «like» operator on this string column for complex multi language matching.

When you are a professional and know what you are doing you can call this an optimization. If your are a newbie then you obviously didn’t know what you done and what the «relation» in relational database systems mean.

Use a join table (also called chain table) to define n-m relations.

Join table for users and languages (pseudo-SQL):

CREATE TABLE user_language

This way you can just get all languages by user ID (and all users which are tied to a specific language). Some RDBMS supports retrieval of those values as a SQL ARRAY type which you in turn can obtain by ResultSet#getArray() in a single query. In PostgreSQL for example you can do the following query:

SELECT u.id, u.name, ARRAY( SELECT l.name FROM language l JOIN user_language ul ON u.id = ul.user_id WHERE l.id = language_id) AS languages FROM user u 

which you can handle in JDBC as follows:

while (resultSet.next()) < Long String name = resultSet.getString("name"); Object[] languages = resultSet.getArray("languages").getArray(); // Cast to String[] or convert to Listor so yourself. > 

Storing several values in a single column is usually not a good idea, since it violates the principles of database normalization.

From your description it sounds like you have a many-to-many relationship. Implementing it by storing several values in a column would force you to work harder than necessary whenever you want to update the column, or query by a language.

It’s technically possible to think of a workaround (as Telcontar suggested, for example), but I would recommend reading a bit about the different normal forms, and reconsidering the database design.

  • Getting Python to return more than one value to Java
  • trying to search for element by more than one property
  • Using more than one build for a single instance
  • How can i write more than 1 database Table into one .csv file using open CSV?
  • How can i write more than 1 database Table into one .csv file using open CSV?
  • Hibernate with more than one dataBase
  • Hibernate with more than one dataBase
  • JPA Sequence Generator causing ORA-01438: value larger than specified precision allowed for this column for Id column
  • JPA Sequence Generator causing ORA-01438: value larger than specified precision allowed for this column for Id column
  • Why is my for loop executing more than once for each time a value is inputted?
  • Returning more than one column in stream?
  • why volatile can’t be used in the case where one more threads will write value
  • why volatile can’t be used in the case where one more threads will write value
  • How do I add more than one text field at position north of my applet
  • In my testNG integration tests can I use @factory more than once (using Jenkins and Maven for my builds)?
  • Handling more than one leading zero
  • I want my method to return more than one character
  • I want my method to return more than one character
  • Hibernate : Insert column value from app instead of database
  • How can I get one database entry with max value using hibernate criteria
  • design a method in Java which receives 2D array and find the most repetitive value for each column
  • How to set id and value for jcombobox when fetching id and value from database
  • Get value from ActionListener from one class for use in another Class
  • Program for finding factorial of a number. Correct but result is printing more than once
  • How i don’t show same window more than one at a time
  • Camel-CXF REST: How to send to CXF web service more than one parameter on payload in REST client?
  • Search if a column value in database exists in a file
  • JSON No Value For Exception Also how to retrieve values if column names are entered by user
  • JSON No Value For Exception Also how to retrieve values if column names are entered by user
  • Sorting an array on more than one criterion

More Query from same tag

  • Is there a way to retrieve information from the camera on an android device?
  • @SessionScoped / @Stateful — how do they managed session/state
  • Stop screen tearing with JavaFX AnimationTimer
  • Read a XML file with XStream
  • JPQL: Postgres entity is not recognized with TABLE_PER_CLASS inheritance
  • How to access values of a line, while reading in a text file in Java
  • How to fetch a single data with sql in java NetBeans
  • Method to check if a Char is present on a specific String
  • Google App Engine endpoints — generate android library — method category() is already defined in class
  • BitBucket repo has file which is not in my src folder
  • How to disable same time selection in jquery
  • Baseball Menu Insertion sort part
  • String literals and String which is acted upon intern() method will go in SCP area. Rest all in heap
  • How to update image in listview for android
  • using spinner in android development
  • Dynamic Dropdown not working in GSP
  • Java Applet JProgressBar not showing
  • I have got this error : Failed to create InitialContext using factory specified in hashtable
  • how to notify a thread from another class
  • Java Schedule a task for single execution
  • Selenium WebDriver POM Handling compound classes
  • fatal exception : asynctask #1 java.lang.runtimeException: an error occured while excuting doinbackground
  • How can I add the value I created from user input and transfer that to a LinkedList?
  • org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘helper’ . No unique bean of type [java.lang.String]
  • Jena; Domains and Ranges for a property differs upon selected Reasoner
  • SOAP WSDL mis-configuration SOAP instead of SOAPENV
  • LibSVM for Android — garbage collect delay
  • ColorPicker opens in background
  • Is it possible to monkey patch a scala final class with an annotation?
  • Using apostrophes in a MySQL query Java

Источник

Java Interview Question Return More Than One Value via object

By using Object as the return value we can group the information we need into the returning object.

In this way we can return more than one value we need.

import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class Voting < final static int MaxCandidates = 7; public static void main(String[] args) throws IOException < Scanner in = new Scanner(new FileReader("votes.txt")); PrintWriter out = new PrintWriter(new FileWriter("results.txt")); Person[] candidate = new Person[MaxCandidates + 1]; // get the names and set the scores to 0 for (int h = 1; h new Person(in.nextLine(), 0); VoteCount count = processVotes(candidate, MaxCandidates, in, out); printResults(out, candidate, MaxCandidates, count); in.close();// ww w . d e m o 2 s . c o m out.close(); > // end main public static VoteCount processVotes(Person[] list, int max, Scanner in, PrintWriter out) < VoteCount votes = new VoteCount(0, 0); // set valid, spoilt counts to 0 int v = in.nextInt(); while (v != 0) < if (v < 1 || v >max) < out.printf("Invalid vote: %d\n", v); ++votes.spoilt; > else < ++list[v].numVotes; ++votes.valid; >v = in.nextInt(); > // end while return votes; > // end processVotes public static void printResults(PrintWriter out, Person[] list, int max, VoteCount votes) < out.printf("\nNumber of voters: %d\n", votes.valid + votes.spoilt); out.printf("Number of valid votes: %d\n", votes.valid); out.printf("Number of spoilt votes: %d\n", votes.spoilt); out.printf("\nCandidate Score\n\n"); for (int h = 1; h "%-18s %3d\n", list[h].name, list[h].numVotes); out.printf("\nThe winner(s)\n"); int win = getLargest(list, 1, MaxCandidates); int winningVote = list[win].numVotes; for (int h = 1; h if (list[h].numVotes == winningVote) out.printf("%s\n", list[h].name); > // end printResults public static int getLargest(Person[] list, int lo, int hi) < int big = lo; for (int h = lo + 1; h if (list[h].numVotes > list[big].numVotes) big = h; return big; > // end getLargest > // end class Voting class Person < String name; int numVotes; Person(String s, int n) < name = s; numVotes = n; >> // end class Person class VoteCount < int valid, spoilt; VoteCount(int v, int s) < valid = v; spoilt = s; >> // end class VoteCount 

  • Java Interview Question Word Frequency Count
  • Java Interview Question Merging Ordered Lists
  • Java Interview Question Using a Class to Group Data: Word Frequency Count
  • Java Interview Question Return More Than One Value via object
  • Java Interview Question Create Linked Lists step by step
  • Java Interview Question Building a Linked List: Adding a New Item at the Head
  • Java Interview Question Building a Sorted Linked List

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Оцените статью