I have App Java and its connect for JDBC and execute this query:
String date = '21-Dec-16';
StringBuilder query = new StringBuilder("SELECT * ");
query.append("FROM TEST WHERE PUBLISHED_DATE='").append(date).append("'");
connection = getConnection(jdbc);
stmt = connection.createStatement();
rs = stmt.executeQuery(query.toString());
syso query => select * from TEST where PUBLISHED_DATE='21-Dec-16'
and error:
java.sql.SQLDataException: ORA-01858: a non-numeric character was found where a numeric was expected
i too test:
select * from TEST where PUBLISHED_DATE=TO_DATE('21-Dec-16','DD-MON-RR')
and error:
java.sql.SQLDataException: ORA-01843: not a valid month
Nevertheless, i execute this query in my sql developer and works!
The immediate cause of your error is that you are using a date format which is incorrect for an Oracle query. But that aside, you should seriously consider using a prepared statement here. In addition to protecting your program against SQL injection, it will also relieve you from worrying about how to format your date for the query. Instead, you can simply bind the direct Java date object to the query.
String query = "SELECT * FROM TEST WHERE PUBLISHED_DATE = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setDate(1, date); // here 'date' is an actual Date object, not a string
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
// access each record
}
If you absolutely must continue down your current road, I would expect the following raw query to run without error:
SELECT * FROM TEST WHERE PUBLISHED_DATE = '2016-12-21'
You could use a Java SimpleDateFormat object to obtain this from a Date object.
If you want to use that format for dates, you have to change the language settings of your database session:
Statement s = connection.createStatement();
s.execute("alter session set NLS_LANGUAGE = 'AMERICAN'");
and then you can use the TO_DATE function as in your second example.
Related
The query inside MySQL is working:
DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'
I can delete data inside MySQL, but the problem is whenever I try to remove the account_tags from my Java application, it throws an error:
java.sql.SQLSyntaxErrorException: 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 'DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'' at line 2
Here's my Java SQL query:
Statement statement = dbConnection.createStatement();
String sql = "SELECT * FROM "+databaseName+"."+tableName+";\n" +
"DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = '"+AccountTag+"';";
statement.executeQuery(sql);
The error isn't giving me much to work with, so I really have no idea what is wrong with the program.
Did you add the allowMultiQueries=true
If not then you can add that while you sending the connecting request to your database. So you need to append the allowMultiQueries=true in your to database URL.
Like this:
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
String sql = "DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
int updateCount = statement.executeUpdate();
System.out.printf("%s: %d records deleted.%n", tableName, updateCount);
}
The only thing used is the DELETE, for which one should use executeUpdate.
One definitely should use a PreparedStatement as many code checkers will give alarms otherwise. It escapes things like ', handles types of the arguments, and possible conversions, and especially is a security feature against SQL injection.
The System.out usage is bad style, better would be using a logger.
try-with-resources automatically closes the PreparedStatement even with a raised exception or break/return.
When doing both database operations, it seems better to use two (prepared) statements, as the first returns a ResultSet.
So:
String sql = SELECT * FROM "+databaseName+"."+tableName + "\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
try (ResultSet rs = statement.executeQuery()) {
...
}
}
Better to separate statements with an If condition :
String sql1="SELECT * FROM "+databaseName+"."+tableName;
String sql2="DELETE FROM "+databaseName+"."+tableName+" "+
"WHERE account_tags = '"+AccountTag+"';
statement.executeQuery(sql1);
statement.executeUpdate(sql2);
In ORACLE(11g), in some package I have a function that returning table:
SELECT * FROM TABLE( my_PKG.fnc_myList());
So it works perfectly in Oracle SQL Developer tool, for example. I got rows from the target table in Query Result of SQL Developer.
Question:
Will it work from JAVA (8) code?
I tried the code below:
con = DriverManager.getConnection(...);
String SQLQ = "{SELECT * FROM TABLE( my_PKG.fnc_myList());}";
Statement st =con.createStatement();
rs=st.executeQuery(SQLQ);
while (rs.next()) {
int id = rs.getInt(0);
String name = rs.getString(1);
....
}
But got the error:
java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
Am I wrong somehwere else or it couldn't work at all through JDBC driver?
You should neither use the braces nor the semi-colon. The braces are sometimes used if only a stored procedure is called. But you have a SELECT statement (even if it contains a function). And the semi-colon is only used in PL/SQL or in tools like SQL developer to separate statements:
con = DriverManager.getConnection(...);
String SQLQ = "SELECT * FROM TABLE( my_PKG.fnc_myList())";
Statement st =con.createStatement();
rs=st.executeQuery(SQLQ);
while (rs.next()) {
int id = rs.getInt(0);
String name = rs.getString(1);
....
}
i want to fetch data from database by using a variable string.it shows error
"Unknown column '$a' in 'where clause'"
String a=request.getParameter("from");
ResultSet resultset= statement.executeQuery("select * from flight where f = $a") ;
If you want to use the value of the a variable where you have $a, you need to use a prepared statement and fill it in:
String a = request.getParameter("from");
PreparedStatement ps = connection.prepareStatement( // Create a prepared statement
"select * from flight where f = ?" // Using ? for where the
); // parameter goes
ps.setString(1, a); // Fill in the value (they
// start a 1, oddly)
ResultSet resultset = ps.executeQuery(); // Execute the query
Note that even though it's a string, you don't put quotes around the ?. The PreparedStatement handles that for you at the DB driver level, in a way that's safe from SQL injection.
why we use setInt with select query instead of using getInt when value is already there in database?
try {
conn = getConnection();
ps = conn.prepareStatement("SELECT * FROM circle where id =?");
ps.setInt(1, circleId);
Circle circle = null;
rs = ps.executeQuery();
if (rs.next()) {
//String s = rs.getString(circleId);
circle = new Circle(circleId, rs.getString("name"));
}
You're setting the value of the parameter to be used in the query. The ? in the SQL represents the parameter, and here you're giving it a value.
When you call getString() later, that's getting a value from the results of the query, which are very different from the parameters sent as part of the query.
Parameterized SQL allows safe inclusion of values into queries, without needing to escape them to prevent SQL injection attacks, or worrying about data type conversions. You should read the JDBC PreparedStatement tutorial for more details.
I have a java code, where i'm doing a SQL request by using prepareStatement
String requete = "select * from VOreservation"
+ " where id_enseignant = ? and date_reservation = ? and id_creneau = ? ";
PreparedStatement pstmt = con.prepareStatement(requete);
pstmt.setInt(1, ens.getIdEnseignant());
pstmt.setDate(2, date);
pstmt.setInt(3, creneau.getIdCreneau());
ResultSet rset = pstmt.executeQuery();
I have a java.sql.sqlException, so It should be a problem with my request, but for me it is fine
The first and last parameters are number in my DB, and the second is a date (and date is here a java.sql.date)
I'm using the driver: oracle.jdbc.driver.OracleDriver
my error is:
Fail to construct descriptor: Unable to resolve type: (my nested table type)
The problem could be with the JDBC driver for the DBMS you are using. Not all drivers implement the standard completely and correctly. There is not enough information in your question to tell what goes wrong.