in addition to returning the db2.get (i) .getEnumDesc () strings which are normal strings.
there are some strings like: 1 - Selected house in db2.get (i) .getEnumDesc ()
I have to cut -> 1 -
I have translated the selected part of the house and then reassembled it.
1 - select house
in practice, in output, not only normal strings have to be returned, but also strings with numbers, ie 1 - select house
in printed output:
es.
house
hello
1 - select
2 - bye
etc...
public void getTraduttoreIt_ENUM_NLS() throws Exception {
List<EnumNls> db2 = getListEnumNls();
List<DizioPt> sqlServer = getListDizioPt();
BufferedWriter scrivi = new BufferedWriter(
new FileWriter("C:/Users/francesco/Desktop/Table_THERA.ENUM_NLS_Sez4.txt"));
System.out.println("-------------------WRITE FILE N°4--------TRANSLATION------------------------");
for (int i = 0; i < db2.size(); i++) {
for (int j = 0; j < sqlServer.size(); j++) {
if (db2.get(i).getEnumDesc().equals(sqlServer.get(j).getKeyword())) {
System.out.println(
"INSERT INTO THERA.ENUM_NLS VALUES" + "(" + "'" + db2.get(i).getAttributeRef().trim() + "'"
+ "," + "'" + db2.get(i).getEnumValue().trim() + "'" + "," + "'" + "en" + "'" + ","
+ "'" + sqlServer.get(j).getTraduzione().trim() + "'" + ")" + ";");
scrivi.write("INSERT INTO THERA.ENUM_NLS VALUES" + "(" + "'" + db2.get(i).getAttributeRef().trim()
+ "'" + "," + "'" + db2.get(i).getEnumValue().trim() + "'" + "," + "'" + "en" + "'" + ","
+ "'" + sqlServer.get(j).getTraduzione().trim() + "'" + ")" + ";");
scrivi.newLine();
scrivi.flush();
}
}
}
scrivi.close();
}
}
in practice, in output, not only normal strings have to be returned, but also strings with numbers, ie 1 - select house
in printed output:
es.
house
hello
1 - select
2 - bye
etc...
What error(s) are you getting?
Could the string returned from db2.get(i).getEnumValue().trim() or sqlServer.get(j).getTraduzione().trim() have a single quote (') in it? In which case your SQL statement has a syntax error. If this is the case, after trim() you could insert a .replaceAll("'", "''") which should solve your the problem.
So db2.get(i).getEnumValue().trim().replaceAll("'", "''") - This is ("\u0027", "\u0027\u0027")
If you are getting a number back, what you have should work, even if the number is part of the string.
Unless your data has to do with "house", I think you are using the wrong English word in describing your situation.
In any case, explain the errors you are seeing and that might help people understand your problem.
Related
I am trying to have a string that when i print it, has multiple lines and different left indents.
String test = "Zone 0:" +
"Gear{" + "gearType=" + gearType + ", weight=" + weight}" +
"Zone 1:" +
"Gear{" + "gearType=" + gearType + ", weight=" +weight}";
System.out.println(test);
Expected Output: (without the dashes but with a left indent)
Zone 0:
------Gear{gearType=RAIN_JACKET, weight=HIGH}
Zone 1:
------Gear{gearType=SHELTER, weight=HIGH}
You can make use of "\n" new line character and "\t" for tab. Like:
final String test = "Zone 0:\n" + "\tGear{" + "gearType=" + gearType + ", weight=" + weight +"}\n" + "Zone 1:\n"
+ "\tGear{" + "gearType=" + gearType + ", weight=" + weight + "}\n";
As well as after weight there should be + sign and a double quote ". (as in above String)
you can use the "\n" for new line and "\t" for tabulation space :
String test = "Zone 0:\n" + "\tGear{" + "gearType=" +
gearType + ", weight=" + "weight}\n" +
"Zone 1:\n" + "\tGear{" + "gearType=" +
gearType + ", weight=" + "weight}";
output :
Zone 0:
Gear{gearType=test, weight=weight}
Zone 1:
Gear{gearType=test, weight=weight}
You may also refer to the official Formatter documentation. There you'll get all the other options and details for formatting a String in Java.
Presumably you'd want the lines to use the appropriate line terminator for your platform, i.e. \r\n for Windows and \n for Linux.
There are two ways to do that:
Use System.lineSeparator():
String test = "Zone 0:" + System.lineSeparator() +
" Gear{gearType=" + gearType + ", weight=" + weight + "}" + System.lineSeparator() +
"Zone 1:" + System.lineSeparator() +
" Gear{gearType=" + gearType + ", weight=" + weight + "}" + System.lineSeparator();
Use String.format(String format, Object... args) and the %n format specifier:
String test = String.format("Zone 0:%n" +
" Gear{gearType=%s, weight=%s}%n" +
"Zone 1:%n" +
" Gear{gearType=%s, weight=%s}%n",
gearType, weight, gearType, weight);
I'd recommend the second approach, since it's more readable.
May be an idea to rather use a StringBuilder (though from what I understand the Java compiler uses StringBuilder under the hood for String concatenation), so it really becomes more of a readability issue.
StringBuilder output = new StringBuilder()
.append(System.lineSeparator()).append("Zone 0:")
.append(System.lineSeparator()).append("\tGear{gearType=").append(gearType).append(", weight=").append(weight).append("}")
.append(System.lineSeparator()).append("Zone 1:")
.append(System.lineSeparator()).append("\tGear{gearType=").append(gearType).append(", weight=").append(weight).append("}");
System.out.print(output.toString());
For newlines it's good practice to use System.lineSeparator()
I have got a webapp(JSP/Servlet) with Tomcat8 + SQL Server2012
JDBC Driver Type 4: JTDS old version 1.2.5 (http://jtds.sourceforge.net/)
I change this kind of query, adding Prepared Statement (server pagining)
Sting DDXsql = "SELECT '?' *, ( DDX_RECORD_COUNT / '?' + 1 ) AS DDX_PAGE_COUNT
FROM
( SELECT '?' *
FROM ( SELECT '?' *,
(SELECT COUNT(*) " + "FROM "
+ session.getAttribute("DatabaseName") + ".G1_grid "
+ sqlFrom
+ sqlWhere + " "
+ " ) AS DDX_RECORD_COUNT "
+ "FROM " + session.getAttribute("DatabaseName") + ".G1_grid "
+ sqlFrom
+ sqlWhere + " "
+ " ORDER BY '?' '?' , '?' '?' ) AS TMP1 ORDER
BY '?' '?', '?' '?') AS r ORDER BY '?' '?', '?' '?'";
Parameters:
String top1 = DBManager.getTOP(request, "TOP " + Integer.valueOf((String)ResourceManager.findData("pageSize", request)));
Integer pagesizeInt = Integer.valueOf((String)ResourceManager.findData("pageSize", request));
String top2 = DBManager.getTOP(request, "TOP " + Integer.valueOf((String)ResourceManager.findData("ddxrecordcount", request)));
String top3= DBManager.getTOP(request, "TOP " + Integer.valueOf((String)ResourceManager.findData("toRange", request)));
String notSortStr = (String)ResourceManager.findData("notSort", request);
Object[] values = new Object[] {
top1,
pagesizeInt,
top2,
top3,
SortKey,
Sort,
TotalSortKey,
Sort,
SortKey,
notSortStr,
TotalSortKey ,
notSortStr,
SortKey,
Sort,
TotalSortKey,
Sort
};
Before, I didint use PreparedStatement I have this kind of query (replace "?" with the Object array values, without StringEscapeUtils):
String DDXsql = "SELECT " +
DBManager.getTOP(request, "TOP "
+ Integer.valueOf(StringEscapeUtils.escapeSql((String)ResourceManager.findData("pageSize", request)))) + " *,
( DDX_RECORD_COUNT / " + Integer.valueOf(StringEscapeUtils.escapeSql((String)ResourceManager.findData("pageSize", request))) + " + 1 ) AS DDX_PAGE_COUNT FROM
( SELECT "
+ DBManager.getTOP(request, "TOP "
+ Integer.valueOf(StringEscapeUtils.escapeSql((String)ResourceManager.findData("ddxrecordcount", request))))
+ " * FROM ( SELECT " + DBManager.getTOP(request, "TOP " + Integer.valueOf(StringEscapeUtils.escapeSql((String)ResourceManager.findData("toRange", request))))
+ " *, (SELECT COUNT(*) "
+ "FROM " + session.getAttribute("DatabaseName") + ".G1_grid " + sqlFrom + sqlWhere + " " + " ) AS DDX_RECORD_COUNT "
+ "FROM " + session.getAttribute("DatabaseName")
+ ".G1_grid " + sqlFrom + sqlWhere + " " + " ORDER BY "
+ StringEscapeUtils.escapeSql(SortKey) + " " + StringEscapeUtils.escapeSql(Sort) + ", "
+ StringEscapeUtils.escapeSql(TotalSortKey) + " "
+ StringEscapeUtils.escapeSql(Sort) + ") AS TMP1 ORDER BY "
+ StringEscapeUtils.escapeSql(SortKey) + " "
+ StringEscapeUtils.escapeSql((String)ResourceManager.findData("notSort", request))
+ ", " + StringEscapeUtils.escapeSql(TotalSortKey) + " "
+ StringEscapeUtils.escapeSql((String)ResourceManager.findData("notSort", request)) + " ) AS r ORDER BY "
+ StringEscapeUtils.escapeSql(SortKey) + " "
+ StringEscapeUtils.escapeSql(Sort) + ", "
+ StringEscapeUtils.escapeSql(TotalSortKey)
+ " " + StringEscapeUtils.escapeSql(Sort) + " ";
The last query runs without error, System.out of this query give this for example:
SELECT TOP 20 *, ( DDX_RECORD_COUNT / 20 + 1 ) AS DDX_PAGE_COUNT
FROM
( SELECT TOP 20 * FROM
( SELECT TOP 20 *,
(SELECT COUNT(*)
FROM SuiteMA_DIP.dbo.G1_grid
WHERE 1 = 1 ) AS DDX_RECORD_COUNT
FROM SuiteMA_DIP.dbo.G1_grid WHERE 1 = 0 ORDER BY DATA_ISCRIZIONE_ORDER DESC, SOGGETTO_RILEVANTE_PAID DESC) AS TMP1 ORDER BY DATA_ISCRIZIONE_ORDER ASC, SOGGETTO_RILEVANTE_PAID ASC ) AS r ORDER BY DATA_ISCRIZIONE_ORDER DESC, SOGGETTO_RILEVANTE_PAID DESC
But when i run sql with preparedStatement:
java.sql.SQLException: Invalid parameter index 1.
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.getParameter(JtdsPreparedStatement.java:340)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.setParameter(JtdsPreparedStatement.java:409)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.setObjectBase(JtdsPreparedStatement.java:395)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.setObject(JtdsPreparedStatement.java:667)
at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:188)
at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:188)
at it.netbureau.jfx.db.SQLDBManager.execSQL(SQLDBManager.java:57)
at it.netbureau.jfx.db.SQLDBManager.execSQL(SQLDBManager.java:78)
at org.apache.jsp.G1.select_jsp._jspService(select_jsp.java:691)
The java method execute the query :
class jfx.db.SQLDBManager.execSQL:
public Object execSQL(PreparedStatement stmt, Object values[], String xmlId)
throws SQLException
{
Object result = null;
if(stmt == null)
return null;
try
{
for(int i = 0; i < values.length; i++)
if(values[i] == null)
stmt.setNull(i + 1, 4);
else
stmt.setObject(i + 1, values[i]); <--this give exception!
if(stmt.execute()) result = transform(stmt.getResultSet(), xmlId);
}
catch(SQLException ex)
{
rollback();
throw ex;
}
return result;
}
What's wrong?
Thank you very much
roby
Your query does not contain any parameters, a '?' is just a literal string with a question mark in it, it is not a parameter.
You also can't parameterize object names like column names and clauses (like a TOP 20), so even if you'd change it to - for example - order by ?, ... it wouldn't work, as you'd be sorting by the string value (which would be the same for all rows, so effectively you wouldn't be sorting at all).
To do what you want to do you will need to concatenate the column names (and other clauses) into the query string. This also means that you might open yourself up to SQL injection: be sure to check the values carefully (for example against a whitelist of allowed values).
Generate by use of the operator + a string, that the values in the variable in the given ones on top
Order includes, in each case apart by ",". give the string with System out println (...).
Remove the quotes " and call toString()
str = hexValue.toString() + ", " + octValue.toString() + ", " + l.toString() + ", " + var1.toString() + ", " + var2.toString() + ", " + var3.toString() + ", " + var4.toString() + ", " + c.toString();
now notice that this will give you the decimal values.. if you want the hex, octal, etc, that's a different question.
Suppose we have the following variables:
int age = 5;
String name = "Mohammad";
double weight = 68.4;
If we want to print them out joined in a string with one statement we can say:
System.out.println("My name is " + name + ", I am " + age + " years old, " + " I once caught a fish that weighs " + weight +"kg");
In Java, using the + operator you can concatenate strings.
Note: age, name, and weight are all of different types, but when you put the + operator with a String, java automatically convert that variable to a string and then concatenates it with the rest of the string. Hence, if you wish to perform some kind of operation then concatenate, then you should make use of parentheses ():
System.out.println("Two Plus Five is = " + (2 + 5));
Lets assume, that we have some 2 tables in SQLite: TBL_PRODUCT and TBL_PRODUCT_ALIASES. Now, I want to query some data from joined two tables:
String sql = "SELECT " + TBL_PRODUCT + "." + C_PROD_PKEY_ID + ", " + TBL_PRODUCT_ALIASES + "." + C_PROD_ALIASES_PKEY_ID +
" FROM " + TBL_PRODUCT + " LEFT JOIN " + TBL_PRODUCT_ALIASES + " ON " + TBL_PRODUCT + "." + C_PROD_PKEY_ID + " = " + TBL_PRODUCT_ALIASES + "." + C_PROD_ALIASES_PKEY_ID +
" WHERE " + C_PROD_SERVER_ID + " = ? LIMIT 1";
Cursor cursor = SQLiteDataHelper.getInstance().rawQuery(sql, new String[] {"" + js_CartProduct.getLong("prod_id")});
Thats works great without any problem. And then I want to acquire some data from the returned cursor:
if (cursor.getCount() > 0) {
cursor.moveToFirst();
Long prodId = cursor.getLong(cursor.getColumnIndexOrThrow(TBL_PRODUCT + "." + C_PROD_PKEY_ID));
//... Some other code
}
Now, here is the problem: C_PROD_PKEY_ID and C_PROD_ALIASES_PKEY_ID are in the real world the same Strings: "_id". And as the result getLong() returns long not from the needed column of cursor.
How should I correctly address to the needed column? Are there other methods besides using AS in sql query OR/AND using definite numbers in cursor.getLong(0) instead of cursor.getLong(cursor.getColumnIndexOrThrow(TBL_PRODUCT + "." + C_PROD_PKEY_ID))?
Update:
cursor.getColumnNames() returns this: [_id, _id].
I would like to insert a carriage return into a cell of a xls file.
So I have written this code
address = rs.getString(16) + " " + rs.getString(17) + "
"
+ rs.getString(18) + " " + rs.getString(19) + " (" +
rs.getString(20) + ")";
"writer.write("<ss:Cell><ss:Data ss:Type=\"String\">" + address + "</ss:Data></ss:Cell>");`
but in the Excel File the result is that the carriage return is replaced with a "square symbol". In which mode can I resolve this issue?
Thanks,
Stefano
In excel, to enter a new line in a cell, you need to insert ASCII characters 13 + 10 (constant CrLf on this page : http://msdn.microsoft.com/en-us/library/f63200h0%28v=vs.80%29.aspx).
Have you tried:
String crLf = Character.toString((char)13) + Character.toString((char)10);
address = rs.getString(16) + " " + rs.getString(17) + crLf
+ rs.getString(18) + " " + rs.getString(19) + " (" +
rs.getString(20) + ")";