I'm blocked on a stupid problem in one of my functions.
I want to get the generatedKey of one of my Sql query. I can't and i don't understand why. The problem is that resultSet.next() it return false even if the line have been inserted when I check the data in the table.
Here is my code :
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO calamar.calamar.application (nom,criticite,autorise) VALUES ('"+nom+"','"+criticite+"','"+false+"');");
ResultSet resultSet = statement.getGeneratedKeys();
resultSet.next();
Solution : Add Statement.RETURN_GENERATED_KEYS
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO calamar.calamar.application (nom,criticite,autorise) VALUES ('"+nom+"','"+criticite+"','"+false+"');", Statement.RETURN_GENERATED_KEYS);
ResultSet resultSet = statement.getGeneratedKeys();
resultSet.next();
Related
I want to do the following query in Postgres using JDBC:
with things as (values(1),(2)) select * from things;
So my Java code looks like this:
String sql = "with things as (?) select * from things";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setArray(1, conn.createArrayOf("INTEGER", new Integer[]{1, 2});
But this is throwing the following error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
You can do what you need using unnest like this:
Integer[] id = {1, 2};
Array array = connection.createArrayOf("int4", id);
try (PreparedStatement stmt = connection.prepareStatement(
"with things as (select unnest((?)::integer[])) select * from things")) {
stmt.setArray(1, array);
ResultSet rs = stmt.executeQuery();
// use the result set
}
Hibernate executeUpdate() for insert or update native query with returning * gives and exception and also does not update the tables.
SQLQuery query = session.createSQLQuery(
"INSERT INTO public.account (username) VALUES ('xx'), ('yy'), ('zz') RETURNING user_id");
Transaction tx = session.beginTransaction();
query.executeUpdate();
tx.commit();
Exception:
org.postgresql.util.PSQLException: A result was returned when none was expected.
executeUpdate() is only appropriate if the SQL statement does not return result rows.
Use iterate(), list() or scroll() instead.
This is the listserializer I am using to create multiple objects.
class listSerializer(serializers.ListSerializer):
def create(self, validated_data):
objs = [klass(**item) for item in validated_data]
return klass.objects.bulk_create(objs)
But bulk_create throws error for unique key error in postgres,So I need to execute this raw sql in same create function.I need help on translating validated_data to sql query.
insert into table (count,value,type,mark,created_at) values
(3,32,2,162,CURRENT_TIMESTAMP),
(4,33,1,162,CURRENT_TIMESTAMP),
(3,33,1,162,CURRENT_TIMESTAMP)
on CONFLICT do nothing
class listSerializer(serializers.ListSerializer):
def create(self, validated_data):
values = ''
for data in validated_data:
values+='('
for item in data.values():
values+=str(item)+','
values+='CURRENT_TIMESTAMP),'
cursor = connection.cursor()
cursor.execute("insert into table (count,value,type,mark,created_at) values "+values[:-1]+"
on conflict do nothing)
I would like to do a check in my PostgreSQL database with Eclipse Link in a named query and return a boolean. However when I change my count statement (which returns a correct value) to a case statement I get a NoResultException. What is the problem?
Following a simplified example:
#NamedQuery(name = "User.isExistent",
query = "SELECT CASE WHEN COUNT(u) > 0 THEN true ELSE false END
FROM User u WHERE u.someField = :someField")
Usage
TypedQuery<Boolean> query = em.createNamedQuery("User.isExistent", Boolean.class);
query.setParameter("someField", "someFieldValue");
Boolean result = query.getSingleResult();
I am currently using "PostgreSQL 9.0.4" database with JDBC driver: "postgresql-9.0-801.jdbc4.jar".
I have the following JDBC SQL using "SELECT... FOR UPDATE OF..." clause which retrieves a column value (long) and updates the value by incrementing in same transaction.
I need to return the long value, thus I need to use SELECT Sql.
final PreparedStatement preparedStatement = _connection.prepareStatement(
"select value from sequence where table_name='JOB' for update of value",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
long ret;
try {
final ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
ret = resultSet.getLong(1);
resultSet.updateLong(1, ret + 1);
resultSet.updateRow();
} catch (SQLException ex) {
ex.printStackTrace();
}
finally {
resultSet.close();
preparedStatement.close();
}
return ret;
All other databases e.g. MySQL, Oracle, MS-SQL, Derby work fine with such SQL - but PostgreSQL always throws following exception.
org.postgresql.util.PSQLException: ERROR: relation "value" in FOR UPDATE/SHARE clause not found in FROM clause
Position: 68
I do have the table "sequence" with the "value" column properly created - so this may not be the infamous case-sensitivity issue.
Does this mean Postgres does not support "SELECT ...FOR UPDATE OF.." SQL syntax?
In that case what will be the best way to achieve the same effect (i.e. select and update with the same transaction)?
Many thanks in advance,
Yes. It is supported. BUT the syntax is
FOR UPDATE [ OF table_name [, ...] ] [ NOWAIT ]
You can see more here:
http://www.postgresql.org/docs/8.2/static/sql-select.html#SQL-FOR-UPDATE-SHARE