I would like to know if when I place a sql query using java , does it retain the new lines?
for instance if i have
"IF EXISTS (SELECT * FROM mytable WHERE EMPLOYEEID='"+EMPID+"')"+
"UPDATE myTable SET ....)"
So after the "+" sign in the first line the UPDATE follows, does it maintain the new line when it is being passed to the database?
Thank you
No. For the query to work successfully you will have to add a space before UPDATE or after ).
Firstly, there is no newline in the example source code to "maintain" ...
Secondly, your problem is with Java rather than SQL. You will only get an newline into a Java String if you put it there explicitly; e.g.
// No newline in this string
String s = "a" +
"b";
// Line break in these strings
String s = "a" + "\n" + "b";
String s2 = "a\nb";
String s3 = "a" + System.getProperty("line.separator") + "b";
Finally, in your example, a space or TAB will do just as well as a line break.
Related
This is a dumb question, but how can I delete a trailing AND in a sql statement in Java?
I'm dynamically generating the statement based on the Profile object I give it. So, if the object has "name = person1" and "address = example road", the statement should be:
select * from Profile where name = 'person1' and address = 'example road'
The issue is that I'm using a for loop to iterate through the declared fields of the object, and so it adds an extra AND to the end:
select * from Profile where name = 'person1' and address = 'example road' and
What would be the best way to get rid of a trailing AND?
You should be using a prepared statement. Building a query like this leaves you open to SQL injection and other attacks.
If you must continue with your current approach, then a quick fix would be to strip off the final AND via regex:
String sql = "select * from Profile where name = 'person1' and address = 'example road' and";
sql = sql.replaceAll("(?i)\\s+and$", "");
Demo
Some would simply trim the final "and" from the end of the resulting string, but it's usually better to avoid writing the final and in the first place.
If your loop looks something like this:
for (String sqlCondition : sqlConditionsList) {
sqlStatement.append(sqlCondition).append(" and ");
}
Then I'd recommend changing it to something like this:
boolean separatorNeeded = false;
for (String sqlCondition : sqlConditionsList) {
if (separatorNeede) {
sqlStatement.append(" and ");
}
sqlStatement.append(sqlCondition);
separatorNeeded = true;
}
This will only add the "and" separator when it's actually needed, between consecutive items from the list you are iterating.
You should use prepared statements or ORM. But if you still want to do that in this error-prone way, you can do it like this:
public static void main(String args[]) {
String[] params = new String[3];
params[0] = "x = y";
params[1] = "z = a";
params[2] = "b = d";
String result = String.join(" and ", params);
System.out.println(result);
}
Using join method is imho better solution than messing with trailing and.
I have a textbox that gives out suggestions based on user input and one of my textboxes is location based.
The problem is, if a user types in Chicago,IL, everything works, but if they type in Chicago, IL, the suggestions stop. The only difference between the two is the space after the comma.
How can I fix this, so that even if a user puts in 2 or 4 spaces after the comma it still shows the same results as the first case?
This is my code:
if (location.contains(",")) {
// the city works correctly
String city = location.substring(0, location.indexOf(","));
// state is the problem if the user puts any space after the comma
// it throws everything off
String state = location.substring(location.indexOf(",") + 1);
String myquery = "select * from zips where city ilike ? and state ilike ?";
}
I have also tried this:
String state = location.substring(location.indexOf(",".trim()) + 1);
The string variables are used to make calls to the database; that is why I have to eliminate any spaces.
How can I fix this, so that even if a user puts in 2 or 4 spaces after
the comma it still shows the same results as the first case?
you can use location.replaceAll(" ", "")
for extracting the location into city,state
you can use split() method as
String location[]=location.split(",");
Now
String city=location[0];
String state=location[1];
EDIT:(for Whome)
String location="New York, NY";
String loc[]=location.split(",");
String city=loc[0].trim();
String state=loc[1].trim();
System.out.println("City->"+city+"\nState->"+state);
you were in the right direction by using trim(). However, you put it in the wrong place.
",".trim() will always yield ",". you want to trim the result of the substring operation:
String state = location.substring(location.indexOf(",") + 1).trim();
Trim the entire result. For example:
String city = (location.substring(0, location.indexOf(","))).trim();
String state = (location.substring(location.indexOf(",") + 1)).trim();
try using java.lang.String trim() function in the correct place.
trim on ",".trim() will produce ",".
Need to trim() the final result.
if (location.contains(",")) {
String city = location.substring(0, location.indexOf(",")).trim();
String state = location.substring(location.indexOf(",")).trim();
}
Use
String state = location.substring(location.indexOf(",") + 1).trim();
Instead of
String state = location.substring(location.indexOf(",".trim()) + 1);
That should work.
In Java, I want to print a label with a String as the input:
String command
= "N\n"
+ "A50,5,0,1,2,2,N,\"" + name + "\"\
+ "P1\n";
But when the input (name) has a double quote character ("), it is blank and prints nothing. I have tried using the replace function:
name.replace('"', '\u0022');
but it doesn't work. I want that double quote printed in label, how can I do this?
Sending the " character in the text field of the EPL string makes the EPL code think it is the end of the string you are trying to print.
So, if you want to send(and print) "hello" you have to put a backslash before each " character and send \"hello\"
You also have to do that for backslashes.
So, your (EPL)output to the printer would have quotes to begin and end the string, and \" to print the quote characters WITHIN the string :
A30,210,0,4,1,1,N,"\"hello\""\n
Also remember you have to escape to characters to build a c# string so in c# it would look like this:
outputEPLStr += "A30,210,0,4,1,1,N,\"\\"hello\\"\"\n";
[which contains 6 escaped characters]
Couple of points:
replace method returns back string after replacing so you should expect something like:
command = command.replace...
quote has special meaning and hence needs to be escaped in Java. You need the following:
name = name.replace("\"", "");
String command
= "N\n"
+ "A50,5,0,1,2,2,N,\"" + name + "\""
+ "P1\n";
System.out.println(command);
suppose I enter katheline\njoseph in a column(datatype- CLOB) of db table.
At the java end , I want the o/p as :
katheline
Joseph
i.e \n should be recognized as a newline character at the java end.
Is there any ONE single method in java to retrieve db column with \n as newline character.
I don’t want to do any manipulations.. for eg. Usage of string Tokenizer class or replace method is not desirable. They work fine but I am looking for a Direct method
\n is just a way you can write the char number 10 ("newline") in a string. If you retrieve that char from DB it will be in your string. You can iterate over the chars and verify it is:
for(int i=0; i<value.length(); i++)
{
char c = value.charAt(i);
int code = value.codePointAt(i);
System.out.println(c + " - " + code);
}
It shound print:
A - 65
B - 66
- 10
C - 67
for:
AB
C
Manual SQL
In SQL: try char(10) or something similar. It depends on the RDBMS.
Replacing in Java
If you can't convert the values in DB to real newlines then you can do:
value.replaceAll("\\\\n", "\\n");
It receives a regex: \\n meaning bar and n
And a replacement: \n
As I'm writing a Java string I must escape bars, so that's why so many bars are used.
Writing values with newline to DB
Never write values as literal SQL:
insert into .... values ('myvalue');
Use params:
insert into... values (?)
and
preparedStatement.setParam(1, myValue);
I am having string like as follow
String first = "UPPER(substr(con.table_name,1,4)) <> 'BIN$' order by name"
String second = "and constraint_type = 'C' "
I have to insert the second string after first string of UPPER(substr(con.table_name,1,4)) <> 'BIN$'
My result
String c = "UPPER(substr(con.table_name,1,4)) <> 'BIN$' and constraint_type = 'C' order by name"
Strings are immutable so first of all you can't change the string referred to by a. You need to create a new string and reassign a to refer to the new string:
To insert the b string before the order by part in the a string, you could do
int i = a.indexOf("order by");
String newString = a.substring(0, i) + b + a.substring(i);
The result is
UPPER(substr(con.table_name,1,4)) <> 'BIN$' and constraint_type = 'C' order by name
Have a look at java.text.MessageFormat.
That allows to have a format string (like UPPER(substr(con.table_name,1,4)) <> 'BIN$' {0} order by name) formatted with parameters (your param would be and constraint_type = 'C').
If you do have control over a, one of the other answers is probably the best way to go around this.
Assuming you have no control on the contents of string a, you could call a.split("order by"), save the two resulting pieces into two variables a1 and a2 and creating a new string with b between a1 and a2. Something like this (untested):
String[] temp = a.split("order by");
String result = temp[0] + " " + b + " order by " + temp[1];
Again, I haven't really tested this, but you get the idea.
On another note, it looks like you're doing some bare sql manipulation there. Don't do this, my friend. Your code will be pretty vulnerable to sql injection. Use prepared statements instead.