What is wrong with the following statement?
String sql = "INSERT INTO tablename (colname) VALUES ($tag$$${a{e^i\\pi}a}$$$tag$);";
Connection connection = DB.getConnection();
Statement st = connection.createStatement();
st.executeQuery(sql);
After execution, there should be a new row int tablename, with $${a{e^i\pi}a}$$ in colname (type: text). But all I get is $${ae^i\pia}$$, that is the expected without the braces.
I tested it in Java 7.11, PostgreSQL 9.1 (x64) on a Windows 7 machine.
Just use prepared statements so you will never have errors with unescaped Strings because SQL does that for you automatically.
st = conn.prepareStatement("INSERT INTO tablename (colname) VALUES (?)");
st.setString(1, "$${a{e^i\\pi}a}$$");
st.executeUpdate();
For additional information you can look at the answer to this question:
Java - escape string to prevent SQL injection
This is caused by the driver's JDBC escaping e.g. to support the {call ...} or {fn ...} syntax.
According to this thread:
http://postgresql.1045698.n5.nabble.com/plpgsql-function-comment-with-single-quote-braces-td5155934.html
you need to call statement.setEscapeProcessing(false) to prevent the driver to parse JDBC escape syntax.
Note that this only happens when using dollar quoting. String literals inside "regular" single quotes are not subject to JDBC escapes (just as values for PreparedStatements)
Related
I have problem with executing query in my Java program. Here is the code:
String selected=offersList.getSelectedValue();
String sql="SELECT * from outcoming_offers where about='"+selected+"'";
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
And when there is single quotes in 'selected' - it is giving me an error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near.....
So I understand why there is error but I am wondering how to make this work. Are there any other ways except concat()?
It's always better approach is to use prepared statements instead of raw SQL string concatenation.
From your example you should write prepared query like below (parameter to pass are replaced with question marks):
String sql="SELECT * from outcoming_offers where about=?";
PreparedStatement ps = con.preparedStatement(sql);
And then just inject parameter values and execute query:
ps.setString(1, selected);
ResultSet rs = ps.executeQuery();
Thanks to this approach you don't have to deal with SQL query string and single quotes, which is very often error-prone and also (very important) your code is not expose to SQL Injection attacks.
More info in documentation: https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html
You are using a Prepared Statement but not passing the required parameter as you should. Change the statement to this:
String sql="SELECT * from outcoming_offers where about=?";
and then pass the parameter:
pst=con.prepareStatement(sql);
pst.setString(1, selected);
This way you set selected as the 1st parameter of the Prepared Statement.
Now you can execute the query:
rs=pst.executeQuery();
I am trying to connect a Java program to IBM's DB2 database, here is the code
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
Connection db2Conn = DriverManager.getConnection("jdbc:db2://localhost:50000/N","R","k");
Statement st=db2Conn.createStatement();
st.executeUpdate("INSERT INTO NTTP VALUES('MANOJ SAINI','iskcon110','Rajasthan','Male','july 2 2014','C')");
I get a syntax error at Statement st = db2Conn.createStatement();
Type mismatch: cannot convert from java.sql.Statement to java.beans.Statement
and more at st.executeUpdate(), as Multiple markers at this line
- The method executeUpdate(String) is undefined for the type Statement
- Syntax error, insert ";" to complete Statement
- Syntax error, insert "AssignmentOperator Expression" to complete
Assignment
- MANOJ cannot be resolved to a variable
- Syntax error, insert ";" to complete Statement
- Syntax error, insert ")" to complete MethodInvocation.
I am new to DB2 and can not figure out what is wrong.
Your SQL syntax might work in a SQL REPL, but in Java those aren't valid String(s) - also you need to escape \ because it's a special character in Java,
java.sql.Statement st=db2Conn.createStatement();
st.executeUpdate(
"INSERT INTO NTTP VALUES('MANOJ SAINI','iskcon110',"
+ "'Rajasthan','Male','july 2,2014',"
+ "'C:\\Users\\Ramveer\\Documents\\res')");
Also, you should consider using PreparedStatement and bind parameters.
First of all the error suggest that you are trying to import Statement from java.beans.Statement instead of java.sql.Statement and second thing try using java.sql.PreparedStatement instead of java.sql.Statement
Something like this :
String sql = "INSERT INTO student(student_id,student_name,class) VALUES(?,?,?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, 7);
statement.setString(2,"MANOJ SAINI");
statement.setString(3,"Rajasthan");
I'm facing an issue with insertion to SQL database from java code.
I'm using INSERT sql query using the java code to enter the data from XML file to SQL database.
You may suppose column named "Description".
Imagine there is a record in XML which contains apostrophe ('). The program crashes due to the error caused by the apostrophe which is included in the data.
I know that manually we can add another apostrophe and make it work, but imagine data of 10.000 records, how can we handle this issue?
Don't do this (string concatenation):
String sql = "insert into MyTable (description) values ('" + value + "')";
Statement st = connection.createStatement();
st.executeUpdate(sql);
Do do this (prepared statement):
PreparedStatement ps = connection.prepareStatement(
"insert into MyTable (description) values (?)"
);
ps.setString(1, value);
pt.executeUpdate();
The value will get correctly escaped for you. Not only does this protect against mishaps like the one you mentioned, it also helps defend you from SQL injection attacks.
Humorous illustration:
Source
You have two options, you should use PreparedStatement and bind your parameter(s). Or, if you really, really, want - you could use StringEscapeUtils.escapeSql(str).
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 have a string value that i have to insert in mysql database. and i have to escape some literal like (' , " ,% ,) in this string so how can i use regex for that
Don't use regex. Use a database library that escapes things for you, and let it handle this.
Don't try to do this yourself. Let the JDBC driver handle it, by using PreparedStatement instead of concatenating an SQL statement using strings yourself. Example:
Connection conn = ...; // Database connection
PreparedStatement ps = conn.prepareStatement("INSERT INTO MYTABLE (NAME, AGE) VALUES (?, ?)");
ps.setString(1, "Jesper");
ps.setInt(2, 38);
ps.executeUpdate();
If you use PreparedStatement, the JDBC driver will take care of escaping the inserted values correctly for whatever brand and version of the database that you use.