简体   繁体   English

MySQL逗号连接字符串在Java中用逗号

[英]Mysql concat string with comma in java

I am trying to concatenate two ID numbers together but add a comma between them to separate from each other. 我正在尝试将两个ID号连接在一起,但在它们之间添加一个逗号以使其彼此分开。 I know the mysql statement to use but I am having difficulty translating this to a string in my java program. 我知道要使用的mysql语句,但在将其转换为Java程序中的字符串时遇到困难。 I can get it to work without the comma but I can't seem to figure out the syntax for adding the comma. 我可以在不使用逗号的情况下使其正常工作,但似乎无法弄清楚添加逗号的语法。

Here is my attempt: 这是我的尝试:

query = "UPDATE table SET idColumn = concat(idColumn, ','"+idNum+") WHERE word = '"+wordVariable+"' ";

To clarify, I have a word table which contains a word column and an ID number column. 为了澄清,我有一个单词表,其中包含单词列和ID号列。 As an example, my ID column might contain a single number as the ID but after multiple concatenations it might look like: 例如,我的ID列可能包含一个数字作为ID,但是经过多次串联后,它看起来可能像这样:

2,5,4,7,1 2,5,4,7,1

Change your query to: 将查询更改为:

query = "UPDATE table SET idColumn = concat(idColumn, ',"+idNum+"') WHERE word = '"+wordVariable+"' ";

I Think you have made mistake on using inverted commas. 我认为您在使用反向逗号时犯了错误。

Or you can add comma after ','. 或者,您可以在','之后添加逗号。

query = "UPDATE table SET idColumn = concat(idColumn, ',' , '"+idNum+"') WHERE word = '"+wordVariable+"' ";

Change : 变更

query = "UPDATE table 
         SET idColumn = concat(idColumn, ','"+idNum+") 
         WHERE word = '"+wordVariable+"' ";

To :

query = "UPDATE table SET idColumn = concat( idColumn, ',', ? ) WHERE word = ? ";

You were missing a , comma after ',' in the concat . 你错过了,以后逗号','concat

And using an instance of PreparedStatement you can set values for query placeholders. 并使用PreparedStatement实例可以设置查询占位符的值。

pst.setInt( 1, idNum );
pst.setString( 2, wordVariable );

And, I think, your data table design is not correct on idColumn . 而且,我认为您的数据表设计在idColumn上不正确。 Instead of storing comma separated values, you better use a normalized form of tables and data. 与其存储逗号分隔的值,不如使用表格和数据的标准化形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM