SQL = "create view CSaccept as select sID, cName from Apply where major = 'CS' and decision = 'Y' ";
stmt.executeUpdate(SQL);
SQL = "create or replace function test1() returns trigger as $$\n" +
"begin\n" +
" update Apply set cName = New.cName where (sID = Old.sID and cName = Old.cName and Apply.major = 'CS' and Apply.decision = 'Y');\n" +
" return Old;\n" +
"end;\n" +
"$$\n" +
"language 'plpgsql';\n" +
"create trigger CSacceptUpdate\n" +
"instead of update of cName on CSaccept\n" +
"for each row\n" +
"execute procedure test1();";
stmt.executeUpdate(SQL);
Hi I am writing a program in java using postgresql, and the error like below keeps popping up in the above SQL statement. What is the problem?
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: INSTEAD OF triggers cannot have column lists
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:473)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:393)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:322)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:308)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:284)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:258)
at SqlTest2.main(SqlTest2.java:270)
SQL = "create or replace function test2() returns trigger as $$\n" +
"begin\n" +
" delete from Apply where sID = old.sID and cName = old.cName and major = 'CS' and decision = 'Y';\n" +
" return Old;\n" +
"end;\n" +
"$$\n" +
"language 'plpgsql';\n" +
"create trigger CSacceptDelete\n" +
"instead of delete on CSaccept\n" +
"for each row\n" +
"execute procedure test2();";
above one works well. I don't know why First one is not working.
Related
I'm trying to run a query, but I get an error when running it.
However, I'm using Intellij and when I use the copy string concatenation to clipboard feature, and run the query in the datagrip, the query runs fine (after putting in the parameters)
The error I am getting is "ERROR: syntax error at or near "tstoredarticle"\n Position: 199"
I find it a bit weird that it's showing there's a line change, after tstoredartiacle but besides that I don't see what's wrong.
What could be some issues that could cause a problem like that?
my query in intellij looks like this:
private ResultSet getHuaweiSqlQuery(Integer intBrandID, Integer intStorageID, Vector<Integer> vecArticleTypes, int iCurrencyID, int iContactSupplierID, int secondaryStorage, BigDecimal exchangeRate) throws SQLException {
return Hibernate3To4Utils.getConnection(session).createStatement().executeQuery("SELECT storedarticleid, "
+ " CASE WHEN storedarticle_storageid = " + intStorageID
+ " THEN id_storedarticleid_replacement ELSE"
+ " (SELECT COALESCE(id_storedarticleid_replacement, storedarticleid)"
+ " FROM etel.tstoredarticle x"
+ " WHERE tstoredarticle.storedarticle_articleid = x.storedarticle_articleid"
+ " AND x.storedarticle_storageid = " + intStorageID + ")"
+ " END as id_storedarticleid_replacement,"
+ " articlename,"
+ " articledescription, CASE WHEN price IS NULL THEN last_innprice*" + exchangeRate
+ " ELSE price END as last_innprice, id_modelids[1] as order_modelid, storedarticleamount-amount_in_order-amount_waiting as disponibelt,"
+ " amount_in_order, amount_in_bestilling, sum(tusedarticle.amount) as ant_artikler, articleid,amount_waiting, location"
+ " FROM etel.tstoredarticle"
+ " INNER JOIN etel.tarticle as b ON storedarticle_articleid = b.articleid"
+ " LEFT JOIN etel.tusedarticle ON usedarticle_storedarticleid = storedarticleid"
+ " AND ((tusedarticle.datesnap >= CAST(now() as date)-" + LOOK_BACK_DAYS
+ " AND usedarticlefromstorage = true) OR waiting = true)"
+ " LEFT JOIN etel.torder ON usedarticle_orderid = orderid AND torder.id_serviceplaceid = " + Constants.SERVICEPLACE
+ " LEFT JOIN etel.tsupplier_price ON id_articleid = b.articleid"
+ " AND tsupplier_price.id_serviceplaceid = " + Constants.SERVICEPLACE
+ " AND tsupplier_price.id_currencyid = " + iCurrencyID
+ " AND tsupplier_price.id_contactid_supplier = " + iContactSupplierID
+ " LEFT JOIN etel.tusedarticle as last_used on storedarticleid = last_used.usedarticle_storedarticleid"
+ " AND last_used.usedarticleid = (select MAX(latest_usedarticle.usedarticleid) from etel.tusedarticle as latest_usedarticle where"
+ " latest_usedarticle.usedarticle_storedarticleid = storedarticleid)"
+ " WHERE storedarticle_storageid IN(" + intStorageID + ", " + secondaryStorage + ") AND b.id_brandid = " + intBrandID
+ " AND id_articletypeid IN (" + getStringFromArray(vecArticleTypes.toArray()) + ")"
+ " AND tstoredarticle.passive <> true"
+ " GROUP BY storedarticleid,id_storedarticleid_replacement, articlename, articledescription, last_innprice, id_modelids[1],"
+ " storedarticleamount, amount_in_order, amount_in_bestilling, articleid,price,amount_waiting, location, last_used.datesnap"
+ " ORDER BY id_storedarticleid_replacement, storedarticleid");
}
and here's the same query after using the copy string concatenation to clipboard feature:
(this runs fine)
SELECT storedarticleid,
CASE WHEN storedarticle_storageid = ?
THEN id_storedarticleid_replacement ELSE
(SELECT COALESCE(id_storedarticleid_replacement, storedarticleid)
FROM etel.tstoredarticle x
WHERE tstoredarticle.storedarticle_articleid = x.storedarticle_articleid
AND x.storedarticle_storageid = ?)
END as id_storedarticleid_replacement,
articlename,
articledescription, CASE WHEN price IS NULL THEN last_innprice*?
ELSE price END as last_innprice, id_modelids[1] as order_modelid, storedarticleamount-amount_in_order-amount_waiting as disponibelt,
amount_in_order, amount_in_bestilling, sum(tusedarticle.amount) as ant_artikler, articleid,amount_waiting, location
FROM etel.tstoredarticle
INNER JOIN etel.tarticle as b ON storedarticle_articleid = b.articleid
LEFT JOIN etel.tusedarticle ON usedarticle_storedarticleid = storedarticleid
AND ((tusedarticle.datesnap >= CAST(now() as date)-42
AND usedarticlefromstorage = true) OR waiting = true)
LEFT JOIN etel.torder ON usedarticle_orderid = orderid AND torder.id_serviceplaceid = ?
LEFT JOIN etel.tsupplier_price ON id_articleid = b.articleid
AND tsupplier_price.id_serviceplaceid = ?
AND tsupplier_price.id_currencyid = ?
AND tsupplier_price.id_contactid_supplier = ?
LEFT JOIN etel.tusedarticle as last_used on storedarticleid = last_used.usedarticle_storedarticleid
AND last_used.usedarticleid = (select MAX(latest_usedarticle.usedarticleid) from etel.tusedarticle as latest_usedarticle where
latest_usedarticle.usedarticle_storedarticleid = storedarticleid)
WHERE storedarticle_storageid IN(?, ?) AND b.id_brandid = ?
AND id_articletypeid IN (?)
AND tstoredarticle.passive <> true
GROUP BY storedarticleid,id_storedarticleid_replacement, articlename, articledescription, last_innprice, id_modelids[1],
storedarticleamount, amount_in_order, amount_in_bestilling, articleid,price,amount_waiting, location, last_used.datesnap
ORDER BY id_storedarticleid_replacement, storedarticleid
Don't use string concatenation with dynamic text values to build a SQL statement.
For one, if the text values are supplied by a user, you're leaving yourself vulnerable to SQL injection attacks, allowing hackers to steal your data and delete your tables.
But you also have problems getting the text values quoted and escaped correctly.
Instead, use a PreparedStatement, where you place ? markers anywhere a dynamic value needs to go. That is the string in the clipboard.
Example: You're doing:
String name = "John";
String sql = "SELECT * FROM Person WHERE name = " + name;
That gives you this text at runtime:
SELECT * FROM Person WHERE name = John
which is wrong, because the text value needs to be quoted:
SELECT * FROM Person WHERE name = 'John'
You could try
String name = "John's Cross";
String sql = "SELECT * FROM Person WHERE name = '" + name + "'";
but that's also wrong, because this new text value has embedded quotes and would produce:
SELECT * FROM Person WHERE name = 'John's Cross'
To get it right, use a PreparedStatement:
String name = "John's Cross";
String sql = "SELECT * FROM Person WHERE name = ?";
PreparedStatement stmt = Hibernate3To4Utils.getConnection(session).prepareStatement(sql);
stmt.setParameter(1, name);
return stmt.executeQuery();
The JDBC driver will take care of any escaping needed, and thereby protects you from both SQL injection attacks and SQL syntax errors.
I am hoping someone can find what is the issue with my query because I am unable to see fault in it and Oracle SQL Developer seems to run the same query as the code in my Java Swing Application just fine.
My query in SQL Developer:
SELECT
ad.ID,ad.Script_Name,ad.Current_Status,
ad.Issues_found_during_run,ad.Testers,
ad.Run_Date,ad.Tools,u.fTag,u.role,
dbms_lob.substr(u.avatar)
FROM
allData ad
INNER JOIN
users u
ON
u.fTag = ad.lastUserWhoUpdated
GROUP BY
ad.ID,ad.Script_Name,ad.Current_Status,
ad.Issues_found_during_run,ad.Testers,
ad.Run_Date,ad.Tools,u.fTag,u.role,
dbms_lob.substr(u.avatar)
ORDER BY
ad.ID ASC;
Which run perfectly and returns the needed records I would be expecting it to.
However, that same query in my Java Swing App does not seem to like it as it gives me the error of:
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended.
My Java Swing App code:
connectToDB();
String query =
"SELECT " +
"ad.ID," +
"ad.Script_Name," +
"ad.Current_Status," +
"ad.Issues_found_during_run," +
"ad.Testers," +
"ad.Run_Date," +
"ad.Tools," +
"u.fTag," +
"u.role," +
"dbms_lob.substr(u.avatar) " +
"FROM " +
"allData ad " +
"INNER JOIN " +
"users u " +
"ON " +
"u.fTag = ad.lastUserWhoUpdated " +
"GROUP BY " +
"ad.ID," +
"ad.Script_Name," +
"ad.Current_Status," +
"ad.Issues_found_during_run," +
"ad.Testers," +
"ad.Run_Date," +
"ad.Tools," +
"u.fTag," +
"u.role," +
"dbms_lob.substr(u.avatar) " +
"ORDER BY " +
"ad.ID;";
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData metaData = rs.getMetaData();
etc..etc..
My structure for those 2 tables is:
SCRIPT_NAME VARCHAR2(100 BYTE)
CURRENT_STATUS VARCHAR2(50 BYTE)
ISSUES_FOUND_DURING_RUN VARCHAR2(150 BYTE)
TESTERS VARCHAR2(30 BYTE)
RUN_DATE DATE
TOOLS VARCHAR2(20 BYTE)
T_SUITE NUMBER(38,0)
NOE2 VARCHAR2(5 BYTE)
NOE3 VARCHAR2(5 BYTE)
ID NUMBER(38,0)
LASTUSERWHOUPDATED NUMBER
DATELASTMOD DATE
FTAG NUMBER(38,0)
ROLE VARCHAR2(15 BYTE)
AVATAR CLOB
So, what could I be missing?
Remove semicolon after the ad.ID like below. You don't need it
"ORDER BY " +
"ad.ID";
I want to insert the SUM of Somme_versee (column in table Versement) in the column Versement_total.
This is a part of my code:
statement.executeUpdate("INSERT INTO Versement ( Nom , Prenom, Date , Somme_versee,Prix_du_logement, Nom_du_projet) VALUES('" + nom.getText() +"','" +prenom.getText() +"','" +date.getText() + "'," + verse.getText() + ", " + "(SELECT Prix_du_logement FROM Client WHERE Nom='"+ nom.getText() +"' AND Prenom='"+ prenom.getText() + "')," + " (SELECT Nom_du_projet FROM Client WHERE Nom='" + nom.getText()+ "' AND Prenom='" +prenom.getText() + "'))");
statement.executeUpdate("UPDATE Versement SET Versement_total= SUM(Somme_versee) " );
When executing I get this error: misuse of aggregate function SUM()
You should never do this in the same table. And it will get worse when the table gets more records. But what you seem to want is:
UPDATE Versement SET Versement_total = (SELECT SUM(Somme_versee) FROM Versement)
I have created a table called CHEMISTID:
private static final String CREATE_TABLE_CHEMISTID = "CREATE TABLE "
+ CHEMISTID + "(" + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_CHEMISTID
+ " TEXT" + ")";
My insert function works properly but when I run a search query to find if a chemistId is already present using the following query statement:
String selectQuery = "SELECT * FROM " + CHEMISTID +" WHERE " + KEY_CHEMISTID + " = "+ chemistID + ";";
Cursor c = db.rawQuery(selectQuery,null);
My logcat displays the following error message:
E/AndroidRuntime(1169): FATAL EXCEPTION: main
E/AndroidRuntime(1169): android.database.sqlite.SQLiteException: no such column: Spain (code 1): , while compiling: SELECT * FROM chemistIdTable WHERE chemistId = Spain;
Where Spain is a particular chemistId that I have dynamically created in my program.
How should I fix my selectQuery String so that it searches in the column name KEY_CHEMISTID for a particular String chemistId?
You need to quote your strings such as Spain in SQL so they get taken as string literals and not column name identifiers. You can use single quotes like 'Spain' for that.
However it's much better to use ? parameter placeholders instead and supply the parameter values in the selection args array, like:
... KEY_CHEMISTID + "=?" ...
c = db.rawQuery(selectQuery, new String[] { chemistID });
You missed single quote,So change
String selectQuery = "SELECT * FROM " + CHEMISTID +" WHERE " + KEY_CHEMISTID + " = "+ chemistID + ";";
to
String selectQuery = "SELECT * FROM " + CHEMISTID +" WHERE " + KEY_CHEMISTID + " = '"+ chemistID + "';";
Recommended solution is to use parameterized query as
Cursor c = db.query(CHEMISTID, null, KEY_CHEMISTID + "=?",
new String[] { chemistID },null, null, null, null);
I need to update my columns using JAVA Handle and create statement, but from what I have researched I need to be using batch if its all (or most) of the columns I desired to update?
This is the code i've written thus far:
private int deletePlayer(Handle handle, String username, String table) {
logger.debug("Deleting from table " + table);
String sqlCommand;
sqlCommand = String.format("UPDATE %s SET rank = 1 "
+ "SET level = 1 "
+ "SET exp = 0 "
+ "SET prof = '' "
+ "SET guild = '' "
+ "SET varname = '' "
+ "WHERE name = :username", table);
handle.createStatement(sqlCommand)
.bind("username", username)
.execute();
return 1;
}
I broke it up to try and pinpoint the problem and found that the MySQL Command:
sqlCommand = String.format("UPDATE %s SET varname = '' WHERE name = :username", table);
And the like is not working. This is more than likely because of the string/char concatenation.
Also, should I be using batch instead?
Stack Trace: [Ljava.lang.StackTraceElement;#15b2043
Please, if you are going to make this post down please tell me why and I will be more than happy to fix it to your liking, or clarify, so that it adheres to the forum conduct/terms of service/ et cetera.
I think you missed the comma between keyword set to update DB values.
sqlCommand = String.format("UPDATE %s SET rank = 1 "
+ "SET level = 1, "
+ "SET exp = 0, "
+ "SET prof = '', "
+ "SET guild = '', "
+ "SET varname = '' "
+ "WHERE name = :username", table);