Mysql concat string with comma in java - java

I am trying to concatenate two ID numbers together but add a comma between them to separate from each other. I know the mysql statement to use but I am having difficulty translating this to a string in my java program. 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. As an example, my ID column might contain a single number as the ID but after multiple concatenations it might look like:
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.
And using an instance of PreparedStatement you can set values for query placeholders.
pst.setInt( 1, idNum );
pst.setString( 2, wordVariable );
And, I think, your data table design is not correct on idColumn. Instead of storing comma separated values, you better use a normalized form of tables and data.

Related

Single quote problem in sqlite on android. Need to solve without replacing quotes

Cursor cursor = database.rawQuery
("SELECT * FROM table where word like '?%'".replace("?",
letter),null);
When there is a single quote in string letter app crashes.
Need to solve without letter.replace(" ' ", " ") because there are words in table with quotes in it.
You are using the statement API incorrectly. You should bind the literal string value you want to appear in the actual query. That is, do this:
String param = letter + "%";
String query = "SELECT * FROM table WHERE word LIKE ?";
Cursor cursor = database.rawQuery(query, new String[] { param });
It is the API's responsibility to correctly escape the LIKE expression you are trying to build.

Use variable for column name in sql query

I'm searching for a word (variable) that occurs in multiple columns of a table. The search has to return the name of the columns in which the word in found.
I could use a foreach loop to go through each column seperately and know the presence of the word in that particular column when the returned cursor isn't null.
The problem is on how to use two different variables (one for column name and one for the word) in SQL query or rawQuery.
My code is as follows:
String[] columnsList = {"col1","col2","col3"};
String[] wordsList = {"fireman","camper","builder"};
for(String i : wordsList){
for(String j : columnsList){
Cursor wordQuery = myDatabaseHandle.rawQuery("Select * from myTableOne WHERE " + j + " = ?",new String[]{i});
if(!(wordQuery==null)){
Toast.makeText(this,j+"is success",Toast.LENGTH_SHORT).show();
}
}
}
But i'm unable to get the answer. I used a seperate string as:
String queryString = "Select * from myTableOne WHERE " + j ;
and in the query,
Cursor WordQuery = myDatabaseHandle.rawQuery(queryString+" = ?",new String[]{i});
But, it's just toasting the names of all columns.
Your error is here:
if(!(wordQuery==null)){
The cursor is never null.
It can contain 0 records, though.
You can check its length by using wordQuery.getCount()
Something like:
if((wordQuery.getCount() > 0)){

error: The column index is out of range: 1, number of columns: 0

I'm trying to solve the problem of doing an insert into a Postgresql table
I looked at this similar question but it did not solve my problem
ERROR : The column index is out of range: 1, number of columns: 0
here is the part of code getting the error:
String query = "INSERT INTO reviews (nbstar, body, author, product_id) VALUES($1,$2,$3,$4)";
PreparedStatement prepareStatement = connection.prepareStatement(query);
prepareStatement.setInt(1, nbStar);
prepareStatement.setString(2, body);
prepareStatement.setString(3, author);
prepareStatement.setInt(4, productId);
boolean executed = prepareStatement.execute();
i tried several times to change the index number but still the same error
and here is the schema of the table:
table schema
can anyone give me an advice ?
thanks.
In the sql query, you want to insert the values for 5 fields (id, nbstar, body, author, product_id) but there are only 4 values VALUES($1,$2,$3,$4).
Update following your edited question, just modify your query as follows:
VALUES($1,$2,$3,$4)
to
VALUES(?,?,?,?)
My problem was that the question mark had single quotes around it and I copy pasted the query from straight sql so I just replaced the string with a ?. For example
Select * from datatable where id = '?'
and I had to change it to
Select * from datatable where id = ?
For me, I had added a comment which included a question mark.
Silly me!
I got that same error because I had the last \n missing in following query, I hope this helps somebody.
" order by mp.id desc\n" +
" limit 1\n" +
" ) as mge_mp\n" +
" )\n" +
"\n" +
"-- #pageable\n",
My last line was
"-- #pageable",
Incase you get this error, for my own issue, I was passing a field ending with a character next to a variable e.g.:
select * from my_schema."my_table" mt
where
mt.field_2 = variable_2
and mt.field_1 = 'variable_1'
[[and cast(mt.date as DATE) = {{date_picked}}]]
-> This failed with an error of:
The column index is out of range: 1, number of columns: 0
Changed to:
select * from my_schema."my_table" mt
where
mt.field_1 = 'variable_1'
and mt.field_2 = variable_2
[[and cast(mt.date as DATE) = {{date_picked}}]]
Please note the variable ending with a quote character has been moved.
-> This worked for me.
For me the issue was having a semicolon at the end of the query string. Something like:
String query = "INSERT INTO reviews (nbstar, body, author, product_id) VALUES(?,?,?,?);";
Notice the ; appended to the end of the query string. The fix is, well, to remove it:
String query = "INSERT INTO reviews (nbstar, body, author, product_id) VALUES(?,?,?,?)";

Use PreparedStatement to build a query

I was wondering if using PreparedStatement.setString() was a good idea (possible, sensible?) to dynamically build a query.
For example :
sql code:
SELECT * FROM table1 WHERE table1.category = ? ?
java code:
ps.setString(1,"category1");
ps.setString(2,"AND table1.category = 'category2'");
Also, would it be possible to do something like:
ps.setString(1,"category1");
ps.setString(2," AND table1.category = ?");
ps.setString(3,"category2");
Best regards
Unfortunately, NO.
PreparedStatements are strictly for values only. Table Names and Column Names (as well as conditions in your example) are not allowed. So the best way to do is to concatenate it with the string.
String others = " AND table1.category = ?";
String query = "SELECT * FROM table1 WHERE table1.category = ? " + others;
java code:
ps.setString(1,"category1");
ps.setString(2,"category2");
Whatever you put inside setString will go within single quotes ' ' and will not be interpreted as a query.

keep column name variable in Java INSERT INTO command with PreparedStatement?

I have the following problem:
I have two tables in one data base which consist of the same columns besides the name of the last column. I want to write data into them using Java.
I want to use the same preparedStatement for both tables, where I check with an if-command whether it is table1 or table2. table2 has amount10 as the name for the last column, table1 has amount20 for it. This number is stored in a variable within my code.
Below you can see a (simplified) example and how I tried to let the column name variable but it doesn't work. Is there any way to fix this without copying the whole statement and manually changing the number variable?
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount`+"number") VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount`+"number" = ? ; ";
PreparedStatement insertDataStmt;
This will not work since variables number and table are not going to be magically injected into your insertData string while you are changing them.
I'd to a method prepareInsertstatement(String table, String number) that would return correct PreparedStatement:
public void prepareInsertStatement(Connection conn, Strint table, String number) {
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount+"number"') VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount+"number"' = ? ; ";
PreparedStatement insertDataStmt = conn.prepareStatement(insertData);
return insertDataStmt;
}
Just remember to close the PreparesStatement when you don't need it any more.
I suppose that reason for that is invalid syntax. When you concatenate string for last column name you use code 'amount' + number. If your number value is 20, than concat result will be
'amount'20 that cause invalid syntax exception. Just move one extra ' after number.
"'amount" + number + "'"
Note: log, or just error that appears during this statement execution would be very useful to find right answer for your question.

Categories

Resources