Java DB2 Sql command throws an error if i have a ' in my String i tried to replace it with a escape sequence but it would not work on the DB2 end any help ? I want the ' to be present in the String.
Error
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-10, SQLSTATE=42603, SQLERRMC=', DRIVER=3.63.123
Java
String FUNC_VP = "Chris O'Connor/Henry/George";
String myQuery = "SELECT DISTINCT(VICE_PRES) FROM EMP_HC WHERE FUNC_VP ='"+funcvp_name.replace("'", "/'")+"'";
Use a PreparedStatement and its setParameter() methods. It will handle things like escaping for you, and you'll never have to wonder how a particular database might handle things. It also prevents SQL injection, so there's no good reason not to use it.
Try
String FUNC_VP = "Chris O''Connor/Henry/George";
To escape an apostrohe on DB2 it seems you have to use two apostrophes
Related
I have a very simple SQL query I need to run
SELECT `id`, `{Document id}` FROM `test`.`test` LIMIT 10;
where {Document id} is a column name. Whenever I run it through MariaDB JDBC, it fails with error unknown escape sequence. From my understanding {CALL ...} is used to call stored procedure with a JDBC CallableStatement.
How do I escape it? I want JDBC to treat it as literal string without special meaning. \ didn't work for me.
As mentioned in deleted answer by #a_horse_with_no_name, there is setEscapeProcessing. But it's not supported by a lot of connectors (example MariaDB).
I have confirmed this issue using mariadb-java-client-2.2.5. It is not an issue with mysql-connector-java-5.1.44 so you might want to report this issue to MariaDB.
Following the suggestion by #JoopEggen in the comments above, I got it to work with MariaDB JDBC by adding sessionVariables=sql_mode=ANSI_QUOTES to the connection string and using
ResultSet rs = st.executeQuery("SELECT \"{Document id}\" FROM test.test");
I want to insert a data using JDBC, whenever I execute the program then it shows me some Mysql error:
Insert statement:
String sql = "INSERT into books(name, isbn, author, category, desc, published) VALUES('"+name+"','"+isbn+"','"+author+"','"+category+"', '"+desc+"','"+book_published+"')";
I am trying to convert the string to date here using :
String yr = year.getSelectedItem().toString();
String mn = month.getSelectedItem().toString();
String dy = day.getSelectedItem().toString();
String book_date = yr+"-"+mn+"-"+dy;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd",
Locale.ENGLISH);
try{
Date book_published = df.parse(book_date);
}catch(...){...}
and it shows me error like :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, published) VALUES('skd flakj','klsdjf askj','kl jasdklfj kl','kls djfklj f' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
Please help me figure out what is the problem here.
Your code is prone to SQL injection attacks due to use of normal query statements. To secure your query use preparedstatement.
As per your query issue, DESC is a reserved word. So you can't use it as column name.View this for complete list of reserved words.
desc is a reserved word for MySQL, which means u can just use it plainly.
To use it without getting an error from MySQL, u should use ` surround the reserved word.
Ps: u SQL statement may suffer from SQL injection if using user-inputed parameters, attackers can use it to get control of ur system.Maybe u should try to hv a look on this one.
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
desc is not a particularly good column name because it's a reserved word in MySQL. I'm not sure if this is the only issue here but you may want to try surrounding desc with ticks, like so:
String sql = "INSERT into books(`name`, `isbn`, `author`, `category`, `desc`, `published`) VALUES('"+name+"','"+isbn+"','"+author+"','"+category+"', '"+desc+"','"+book_published+"')";
It's good practice anyway.
Edit: and as others have mentioned, prepared statements are safer when saving untrusted input to a database.
I am converting an existing program from JDBC-ODBC Bridge to UCanAccess. It has been working for years. The Java program writes to an MDB file. After conversion, one Insert command stopped working.
It throws "net.ucanaccess.jdbc.UcanaccessSQLException: unexpected token: [".
After some experimentation I determined that the problem is caused by three columns that include apostrophes in their names. Example: [Sched'd PO Place Date]. Apparently JDBC-ODBC Bridge did not care but UCanAccess does.
I am somewhat trapped with the existing MDB structure or I'd simply rename the fields. But there is no telling how many downstream reports could be broken if I did that. The MDB is used for Ad Hoc reporting.
Here is a simplified SQL Select version of the problem. It throws the same error as the Insert.
String cJD = "net.ucanaccess.jdbc.UcanaccessDriver";
String cS = "jdbc:ucanaccess://C:/MosAll/mosall.mdb";
String uid = "";
String pw = "";
String sql4 = "select [Sched'd PO Place Date] from [Tier 1] ";
Class.forName(cJD);
Connection con = DriverManager.getConnection(cS, uid, pw);
PreparedStatement pstmt4;
pstmt4 = con.prepareStatement(sql4);
pstmt4.execute();
Is there a way to "escape" the apostrophes or reconfigure ucanaccess so that the driver can execute them?
This issue has been fixed in UCanAccess 2.0.9.4.
Previous answer:
I have been able to recreate the issue with UCanAccess version 2.0.9.3.
select [Sched'd PO Place Date] ...
fails, but for now simply omitting the '
select [Schedd PO Place Date] ...
works okay. Interestingly, using backticks instead of square brackets
select `Sched'd PO Place Date` ...
also produces the exception
net.ucanaccess.jdbc.UcanaccessSQLException: unexpected token: [
With luck this will get fixed in a future release of UCanAccess.
have you tried table, columns names between `` (they not apostrophe but the one next to ~), the \' may work, and finally the JDBC standard way is to define the escape character at the end of the query:
String sql4 = "select [Sched\'d PO Place Date] from [Tier 1] { escape '\'}"
You may want to try the one above also with ``instead of []
Finally, your last resource is "select *" and extract the right column yourself
I am using a JDBC connection to fetch data from an Access database.
The database design is not my control. In the database there are columns that have "?" included in their names, for example: Open?, Paid?, and lots more.
When I try to fetch data with a PreparedStatement it gives me an error. The query is:
SELECT Open? FROM tblJobList WHERE WeekEnding=?
I also tried to use brackets like [Open?], but the result is the same.
The error I receive is "Too few parameters ..." as I am pushing only one parameter into the PreparedStatement.
I can not use normal statement because of WeekEnding=? as this value is a Timestamp and I could not manage to work it with Statement. Only prepared statement works here.
Can anyone tell me how to use these kind of column names in a PreparedStatement?
use the " character
"SELECT \"Open?\" FROM tblJobList WHERE WeekEnding=?"
tested this against oracle and appears to work with mssqlserver
How to select a column in SQL Server with a special character in the column name?
Just to update this for current technologies:
While the JDBC-ODBC Bridge and Access ODBC were unable to handle a PreparedStatement with a column name containing a question mark, the UCanAccess JDBC driver handles it just fine, as can be confirmed with the following code:
String connectionUrl = "jdbc:ucanaccess://C:/Users/Public/UCanAccessTest.accdb";
Connection conn = DriverManager.getConnection(connectionUrl);
String sql = "SELECT ID, [Open?] FROM tblJobList WHERE WeekEnding=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, java.sql.Date.valueOf("2016-01-01"));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.printf("%d: %s%n", rs.getInt("ID"), rs.getBoolean("Open?"));
}
conn.close();
For more information on UCanAccess, see
Manipulating an Access database from Java without ODBC
I am not sure but you can try // to escape the special meaning of ? and to use it as a normal character. Like:
"SELECT Open//? FROM tblJobList WHERE WeekEnding=?"
You can get something similar to your problem here:
Round bracket in string with JDBC prepared statement
Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.
I'm trying to track the amount of redo being generated during a database session with the following query:
SELECT a.name, b.VALUE
FROM v$statname a, v$mystat b
WHERE a.statistic# = b.statistic# AND a.name = 'redo size';
This query works directly in SQL*Plus and Toad, but I get an ORA-00911 exception using JDBC, and I've narrowed it down to the "statistic#" column name.
How do I get around this?
The column name statistic# is not the problem.
My bet is that you also send the terminating ; from inside your Java program.
But you may not include the the ; when executing a SQL statement through JDBC (at least not in Oracle and some other DBMS).
Remove the ; from your SQL String and it should be fine.
put it in double quotes - that should let you call a field anything in Oracle
Switch on JDBC logging, check your driver documentation for how to do this. In the JDBC log you see the actual statement prepared and executed in the DB. This eliminates one possible cause for the error.