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.
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);
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.
I have looked at several link to retrieve the id with an insert using java, and I thought I would use the RETURNING clause.
my code:
Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory", "postgres","root");
String sql = "INSERT INTO main (nom_fichier, adate, mdate, cdate, size, chunknumber)"
+ " VALUES ('test',450,450,450,450,5)"
+ " Returning id"
+ ";";
Statement stmt = c.createStatement();
int rowNumber = stmt.executeUpdate(sql);
But I get this error:
Exception in thread "main" org.postgresql.util.PSQLException: a result was returned when none was expected.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:339)
at fr.infotel.postgre.TestPostgre.main(TestPostgre.java:25)
I also tried to use the Statement.RETURN_GENERATED_KEYS (withouth Returning clause) without success (I had nothing in the result set).
First Question: I would like to make the RETURNING statement work, as my request works in psql
Second Question: If the first is not possible, how can I have the same result
I am using postgres 9.3 with the postgres9.3.jdbc3 jar.
Thanks for your help.
Use ResultSet object instead of rowNumber
ResultSet resultSet = stmt.executeQuery(sql);
your query result now in resultSet variable.
I'm trying to execute a stored procedure without input variables like :
String sql2 = "{call vivek}" ;
System.out.println(sql2);
System.out.println("Executing procedure without parameters");
stmt = conn.createStatement();
stmt.executeQuery(sql2);
But its throwing an error saying :
syntax error at or near "{"
Position: 1
I'm trying to google it but not able to find anything. How do I do it ? By the way it didn't work with callablestatement also
Not tested:
CallableStatement cs = null;
cs = conn.prepareCall("{call vivek}");
cs.executeQuery();
http://docs.oracle.com/javase/tutorial/jdbc/basics/storedprocedures.html
It's similar to calling a function without arguments.
CallableStatement cat = null;
con = YourConnectionClass.getConnection();
cst = con.prepareCall("{call YOUR_PROCEDURE_NAME()}");
cst.executeQuery();
Could not find stored procedure? I will explain what it means when you get this error. Assuming our code is like this:
String sp="{call GetUnitReferenceMap}";
stmt=conn.prepareCall(sp);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
currencyMap.put(rs.getString(1).trim(), rs.getString(2).trim());
I have 4 DBs (sample1, sample2, sample3), but stmt will search location master (Default DB) then we will get an Exception.
We should provide DB name, then problem will be resolved::
String sp="{call sample1..GetUnitReferenceMap}";
Thanks for the help everyone but the following code worked for me :
sql2 += "{exec "+ proc_name2 +"}" ;
cstmt = conn.prepareCall(sql2);
cstmt.executeUpdate();
Here cstmt is the CallableStatement object by the way. And I'm using Postgresql Database hence the above code worked for me
I've started using prepared statement for my sql updates, but I seem to be getting a snag when I'm updating. The logic seems sound but I get an error whenever it goes into the update segment. I can delete or insert fine. Anywho...
Connection con = getDBConnection();
PreparedStatement pstmt = null;
String query = "update table set int = ?, String= ? where int= ? and date= ?";
pstmt = con.prepareStatement(query);
pstmt.setInt(1, var);
pstmt.setDate(2, sqlDate);
pstmt.setInt(3, intVar);
pstmt.setString(4, stringVar);
pstmt.executeUpdate();
Am I doing something wrong here? I've done all the troubleshooting I can and everything seems fine except for this, potentially.
Error = "A non-numeric character was found where a numeric was expected"
You've got your string and date the wrong way round - you're calling setDate(2, ...) when the second parameter is in the context of "String = ?" and setString(4, ...) when the fourth parameter is in the context of "date = ?".
Admittedly the error you're getting is somewhat odd for that, but it's all I can see...