I'm using postgresql to host my database. In my database, I have a table say xyz whose structure is as shown below
id content folder
1 hello Inbox
2 hi Sent
I want to export this table to CSV using my java program. The code snippet is below
Connection connection2 = new ServerDBConnect().getConnection();
PreparedStatement statement = connection2.prepareStatement("copy (SELECT * FROM xyz WHERE folder=? ) to 'C:/export.csv' delimiter ','");
statement.setString(1, FOLDER_SELECTED); //Here, FOLDER_SELECTED=Inbox
statement.execute();
When I execute this code, I'm getting SQLException saying
ERROR: there is no parameter $1
If I execute the code without folder specified ("copy (SELECT * FROM xyz) to 'C:/export.csv' delimiter ','")), the code works fine.
What am I doing wrong here? How to go about this problem?
Note: If I execute the query (copy (SELECT * FROM xyz WHERE folder='Inbox' ORDER BY time) to 'G:/export.csv' delimiter ',') directly in the Postgresql SQL console, I'm getting the desired output.
Please help
Ah
I finally found the answer myself.
Small change in the query gave me the desired result
The query is suppose to be like this
Connection connection2 = new ServerDBConnect().getConnection();
PreparedStatement statement = connection2.prepareStatement("copy (SELECT * FROM xyz WHERE folder='" + FOLDER_SELECTED + "' ) to 'C:/export.csv' delimiter ','");
This was driving me crazy, but finally done :-)
Related
I'm having issues dealing with the single quote while using it in a prepared statement in JAVA via Oracle JDBC.
Let's say we have a table Restaurant with a column restaurant_name with 1 value : Jack's Deli
I want to use a simple prepared statement query like this:
String result = "Jack\'\'s Deli"
String sqlStatement = "select * from Restaurant where restauraunt_name like ? escape '\\' ";
PreparedStatement pStmt = conn.prepareStatement(sqlStatement);
pstmt.setString(1, result);
The result shows 0 returned values, however when I directly search the query in the database (ORACLE) it works fine and retrieves the result. (Oracle uses two single quotes as an escape for the first)
I am thinking that the value is not being passed properly to the database. Or there is some other formatting issue.
The point of prepared statements is that you don't need any escaping.
.setString(1, "Jack's Deli") will get it done.
I have this sql query which runs fine and return 3 rows when run on sql developer but when I execute the same query in a jsp page, it executes properly but doesn't return any rows. There is no problem with database connection because all other queries work fine.
Server - Tomcat 7
database - Oracle 10g
query -
select slno from lbk_tab where log_date = to_date('18-06-2017','DD-MM-YYYY')
jsp -
String dtol = "select slno from lbk_tab where log_date = to_date('18-06-2017','DD-MM-YYYY')";
Statement st = connection.createStatement();
ResultSet resultSet = st.executeQuery(dtol);
if (resultSet.next()) {
out.print(Integer.parseInt(resultSet.getString(1)));
}
Table lbk_tab has columns slno and log_date.
How can I fix this?
Try these things :
Classfiles are being generated afresh ? Clear & re-build project /
workspace.
Print the query and try to run printed query. Theoretically it looks the same from code, but just to be sure..
Check for query being fired at database also, may be java messes
with date object or date format. Hence the actual date fired from jsp says something else while fired at mysql points at something else ? debug / log / print query actually fired at mysql
end.
More clarity is required here, "to_date" referenced in query is
function ? what are column types.
I Think you need to use to_char()
select slno from lbk_tab where log_date = to_char(to_date('18-06-2017','DD-MM-YYYY'))
I have a search query which must search a column in a table using contains search. There is ctxsys.context type index on the column. While fetching data on the table using prepared statement, the search query is not able to process special characters like -,/,_ etc.
Here is my code -
String query = "select * from parties where contains (party_name ,'%' || ? || '%')>0";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, searchName);
The code works fine for text which doesn't have special characters.
When I run the below query in sqlDeveloper it runs fine .
select * from parties where contains(party_name,'c/o')>0;
Please suggest what changes should I make in the prepared statement to make it work for special characters too.
Please refer to this question on how to use contains in prepared statement.
PreparedStatement with CONTAINS query
You have to use escape in your queries if the above didint work
like
SELECT * FROM BIRDS WHERE SPECIES='Williamson's Sapsucker
statement.executeQuery("SELECT * FROM BIRDS WHERE SPECIES='Williamson/'s Sapsucker' {escape '/'}");
reference from http://www.jguru.com/faq/view.jsp?EID=8881
I am trying to do the following query:
String query = "SELECT * FROM EMP WHERE UCASE(LAST_NAME) ";
query += "LIKE '" + lastName.toUpperCase() + "%'";
in an example of usage of an servlet to access to a database
But I am getting the error message:
Excepcion java.sql.SQLSyntaxErrorException: ORA-00904: "UCASE": invalid identifier
On the other hand, when I use the UPPER sql function, the example works but the results do not show the values of the LASTNAME column in uppercase. I do not understand what happens.
You're just comparing the upper case values, but you're selecting the actual values with select *
to get the uppercase name in your resultset you need to use UPPER in your select list, not UCASE, like this:
String query = "SELECT UPPER(LAST_NAME) AS UPPERNAME, * FROM EMP WHERE UPPER(LAST_NAME) ";
query += "LIKE '" + lastName.toUpperCase() + "%'";
What your code is doing here is building a query string named query. Once query is complete, it will be sent to the database for parsing and running.
When you are building a query to the database, you have to use the built-in database functions for the part of the query that the database is going to parse and run. So, in your example, Java is doing toUpperCase on lastName and then putting that literal into the query string that will go to the database. UPPER(LAST_NAME) is going into the query string as is, it will get passed to the database just like that and run by the database. So it needs to be a function that the database can parse and run: an Oracle function, not a Java function.
UCASE is a DB2 function & not Oracle. For Oracle, you need to use UPPER .
Second part of your question is already answered by James Z.
Having said that, I am answering because previous answers didn't pointed out SQL injection problem with the way you listed your query.
Make it a habit to always execute parametrized queries with jdbc & not by directly appending values to query string.
String query = "SELECT * FROM EMP WHERE UCASE(LAST_NAME) LIKE ? ";
Your parameter would be - lastName.toUpperCase()+"%"
SQL Injection
I am trying to use a Java application (which I do not have the source code for) to output the results of a call to a stored procedure into a text file.
This file works for other similar stored procedures in the system, but I can't seem to get it to produce anything for my new text file other than this exception:
ResultSet is from UPDATE: No Data
I've simplified the body of the stored procedure to a simple select 'Hello World!' and even that doesn't seem to be able to be written out.
Is there anything I can do within the stored procedure to produce results in a fashion that Java will accept?
I encountered this java.sql.SQLException. In my case I was running a query in this way:
String query =
"-- a classical comment " +
"select * " +
"from MYTABLE ";
ResultSet rs = conMain.createStatement().executeQuery(query);
while(rs.next()) {
//do something...
}
rs.next() throws the exception. The reason is that, due to the comments, query results to be:
"-- a classical comment select * from MYTABLE "
hence it's all commented... query is invalid! Many examples could be shown with this mistake (with the comment in the middle of the query etc.).
Solutions: add a \n at the end of each line of the query or use comments in the /*...*/ form.
I selected an older version of the driver an it worked for me.
http://dev.mysql.com/downloads/mirror.php?id=13598 (mysql-connector-java-5.0.8.zip)