Related
I have java application that execute native query, I have tried to execute the query using entityManager.createNativeQuery, jdbcTemplate, and java.sql.PreparedStatement.executeUpdate, none succeeded. The query completed without error, but no data is inserted.
Here's my actual SQL:
WITH stmt AS (
INSERT INTO account_statements (
amount,
sum_amount,
available_balance,
previous_available_balance,
hold_amount,
previous_hold_amount,
type,
note,
partner_id,
incoming_transfer_id
)
(
SELECT
?,
?,
(available_balance + ?),
available_balance,
hold_amount,
hold_amount,
?,
?,
?::uuid,
?::uuid
FROM account_statements
WHERE partner_id = ?::uuid
ORDER BY created_at
DESC LIMIT 1
) RETURNING id, available_balance, hold_amount), debit AS (
INSERT INTO journals (
amount,
type,
account_name,
account_statement_id,
partner_id
) (
SELECT
?,
?,
?,
id,
?::uuid
FROM stmt
)
), credit AS (
INSERT INTO journals (
amount,
type,
account_name,
account_statement_id,
partner_id
) (
SELECT
?,
?,
?,
id,
?::uuid
FROM stmt
)
)
UPDATE partners
SET
available_balance = (select available_balance from stmt),
hold_amount = (select hold_amount from stmt)
WHERE id = ?::uuid;
Not sure what I did wrong, but when I tried the SQL above in pg console and replace all the placeholders, it worked. Does anyone have an idea why the SQL above is not working?
I am trying to insert new entries into my database, but only the new entries. If a class with the crn that I am adding already exists in the database then I would like to skip it to not have duplicates.
Below is the code I have right now. I have tried a few different methods but I keep getting exception:
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 'EXCEPT crn' at line 1
The database entry works fine without the "EXCEPT crn", but again it adds duplicates.
try {
String query = null;
try {
query = "INSERT INTO Classes (crn, subject, creditHours, title, capacity, instructor, schedule) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?) EXCEPT crn";
} catch(Exception e) {
conn.close();
}
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, crn);
preparedStmt.setString(2, subject);
preparedStmt.setInt(3, creditHours);
preparedStmt.setString(4, title);
preparedStmt.setString(5, capacity);
preparedStmt.setString(6, instructor);
preparedStmt.setString(7, schedule);
preparedStmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
If a class with the crn that I am adding already exists in the database then I would like to skip it to not have duplicates.
In MySQL, I would recommend the insert ... on duplicate key syntax:
INSERT INTO Classes (crn, subject, creditHours, title, capacity, instructor, schedule)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE crn = VALUES(crn);
For this to work, you need a unique constraint (or the like) on column crn:
ALTER TABLE Classes ADD CONSTRAINT cs_classes_uniq_crn UNIQUE(crn);
Then, when an INSERT occurs that would generate a duplicate crn, the query goes to the UPDATE clause, that actually performs a no-op.
Can you alter the row or rows you want? You could just put a unique constraint on them so they can't accept columns that have the same value.
ALTER TABLE table_name
ADD UNIQUE (column_name);
If you need multiple columns you can add the constraint to the table like this:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, etc);
The SQL statement that you try to execute is invalid because MySql does not support EXCEPT.
Since you want to skip the insertion of rows that already exist you can use INSERT IGNORE:
query = "INSERT IGNORE INTO Classes (crn, subject, creditHours, title, capacity, instructor, schedule) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
but for this to work there should be a unique constraint for the column crn.It seems like it is the PRIMARY KEY of the table so it is already unique.
If there isn't a unique constraint for the column crn you can use NOT EXISTS like this:
query = "INSERT INTO Classes (crn, subject, creditHours, title, capacity, instructor, schedule) "
+ "SELECT ?, ?, ?, ?, ?, ?, ? "
+ "WHERE NOT EXISTS (SELECT 1 FROM Classes WHERE crn = ?)";
so you will have to pass as the 8th parameter of the Prepared Statement crn again:
preparedStmt.setInt(8, crn);
I need to insert into three tables at once for now. But in the future I will be inserting in more than three tables.
All the three tables have same columns and same data types. So I can insert the same data into three tables as well. Currently I am inserting into one table.
I am working with new database named XpressMP. And it supports all the major SQL syntax.
public final static String INSERT_SQL = "INSERT INTO COPY"
+ "("
+ "ID, ACCOUNT) VALUES"
+ "(?, ?)";
preparedStatement = dbConnection.prepareStatement(INSERT_SQL);
preparedStatement.setString(1, id);
preparedStatement.setString(2, ACCOUNT);
What will be the best way to insert into three tables at once? It is possible to do in a SQL? Or I need to make a change in the Java code to insert into multiple tables?
You cannot parameterize the table name part. You can create String with tablename and ?, then use that string for preparedStatement.
String tablename="COPY";
public final static String INSERT_SQL = "INSERT INTO " + tablename
+ "("
+ "ID, ACCOUNT) VALUES"
+ "(?, ?)";
preparedStatement = dbConnection.prepareStatement(INSERT_SQL);
preparedStatement.setString(1, id);
preparedStatement.setString(2, ACCOUNT);
public static boolean saveUserInfo(Client c){
try {
Statement statement = conn.createStatement();
ResultSet group = statement.executeQuery("SELECT * FROM users WHERE username = '"+ c.playerName + "'");
if (!group.next())
statement.execute("INSERT INTO `users` (`username`, `password`, `rights`, `address`, `hasbankpin`, `bankpin1`, `bankpin2`, `bankpin3`, `bankpin4`, `height`, `posx`, `posy`, `cbowcount`, `vls`, `skulltime`, `ep`, `dpoints`, `vlsleft`) VALUES ('"+c.playerName+"', '"+c.playerPass+"', '"+c.playerRights+"', '"+c.getIP()+"', '"+c.hasBankPin+"', '"+c.bankPin1+"', '"+c.bankPin2+"', '"+c.bankPin3+"', '"+c.bankPin4+"', '"+c.heightLevel+"', '"+c.absX+"', '"+c.absY+"', '"+c.crystalBowArrowCount+"', '"+c.degradeTime+"', '"+c.skullTimer+"', '"+c.earningPotential+"', '"+c.dungeonPoints+"', '"+c.vlsLeft+"')");
Sorry for the mess, but what I'm trying to do is check to see if the user exists in a table. If so, I would like it to update it, if not I would like it to add the user. I have been trying at this for a couple days now and I haven't had any luck.
Any help is much appreciated!
you can do it in a sinlge query using ON DUPLICATE KEY UPDATE clause:
INSERT INTO table_name(...)
VALUES(...)
ON DUPLICATE KEY UPDATE col = value, ...;
you need to put a PRIMARY or UNIQUE key on column username:
ALTER TABLE users ADD UNIQUE KEY ix1 (username);
Your code is vulnerable to SQL Injection. In order to avoid that, use JAVA PreparedStatement. Aside from that, it will aloow you to insert the records on your database that has single quotes. An example of Prepared Statement is like this:
PreparedStatement updateSales = con.prepareStatement(
"INSERT INTO tableName(colA, colB) VALUES (?, ?)");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
Remember to always sanitize your inputs.
back in your question, you can use INSERT...ON DUPLICATE KEY UPDATE
Example, (your username must be UNIQUE)
INSERT INTO `users` (`username`, `password`, `rights`,
`address`, `hasbankpin`, `bankpin1`,
`bankpin2`, `bankpin3`, `bankpin4`, `height`,
`posx`, `posy`, `cbowcount`, `vls`, `skulltime`,
`ep`, `dpoints`, `vlsleft`)
VALUES ('','', .....other values...., '')
ON DUPLICATE KEY
UPDATE `password` = '',
`rights` = '',
... other values here
If you have a unique key, say on username, then you could do something like this:
String query="
INSERT INTO users SET
username = ?,
password = ?,
rights = ?,
address = ?,
hasbankpin = ?,
bankpin1 = ?,
bankpin2 = ?,
bankpin3 = ?,
bankpin4 = ?,
height = ?,
posx = ?,
posy = ?,
cbowcount = ?,
vls = ?,
skulltime = ?,
ep = ?,
dpoints = ?,
vlsleft = ?
ON DUPLICATE KEY UPDATE
password = VALUES(password),
rights = VALUES(rights),
address = VALUES(address),
hasbankpin = VALUES(hasbankpin),
bankpin1 = VALUES(bankpin1),
bankpin2 = VALUES(bankpin2),
bankpin3 = VALUES(bankpin3),
bankpin4 = VALUES(bankpin4),
height = VALUES(height),
posx = VALUES(posx),
posy = VALUES(posy),
cbowcount = VALUES(cbowcount),
vls = VALUES(vls),
skulltime = VALUES(skulltime),
ep = VALUES(ep),
dpoints = VALUES(dpoints),
vlsleft = VALUES(vlsleft)
";
Statement stmt = conn.prepareStatement(query);
stmt.setString(1, c.playerName);
stmt.setString(2, c.playerPass);
stmt.setString(3, c.playerRights);
stmt.setString(4, c.getIP());
stmt.setString(5, c.hasBankPin);
stmt.setString(6, c.bankPin1);
stmt.setString(7, c.bankPin2);
stmt.setString(8, c.bankPin3);
stmt.setString(9, c.bankPin4);
stmt.setString(10, c.heightLevel);
stmt.setString(11, c.absX);
stmt.setString(12, c.absY);
stmt.setString(13, c.crystalBowArrowCount);
stmt.setString(14, c.degradeTime);
stmt.setString(15, c.skullTimer);
stmt.setString(16, c.earningPotential);
stmt.setString(17, c.dungeonPoints);
stmt.setString(19, c.vlsLeft);
stmt.executeUpdate();
Hello friends i am running code given below which contains the setLogTimeEntery function and when this function is executed i am getting
"Error : java.sql.SQLException: ORA-00917: missing comma"
error and my database is oracle plese any one tell me wht is the problem.
public int setLogTimeEntery(Connection con, LogTimeBean ltb) {
int ans = 0;
try{
psmt=con.prepareStatement("Insert into TR_LogTime values((Select count(*) from Tr_LogTime) + 1 ,(select sysdate from dual) , Prj_Id=?,Area_Id=?,Actvity_Id=?,ID_No=?,Work_Date=(select to_date(?,'dd/mm/yyyy')from dual) ,Work_Hours=?,Division=?,Description=?,Remarks=?,Work_Week=?)");
psmt.clearParameters();
psmt.setString(1,ltb.getLt_Prj_Id());
psmt.setInt(2,ltb.getLt_Area_Id());
psmt.setInt(3,ltb.getLt_Actvity_Id());
psmt.setInt(4, ltb.getLt_ID_No());
psmt.setString(5, ltb.getLt_Work_Date());
psmt.setFloat(6,ltb.getLt_Work_Hours());
psmt.setInt(7,ltb.getLt_Division());
psmt.setString(8, ltb.getLt_Description());
psmt.setString(9, ltb.getLt_Remarks());
psmt.setInt(10, ltb.getLt_Work_Week());
ans=psmt.executeUpdate();
psmt.close();
}catch(Exception e){
System.err.println("Error : "+e);
}
return ans;
}
I don't think your Oracle SQL statement (as defined in the prepared statement) is valid. When using the insert into [table] values(...) syntax, you don't use column=value expressions.
If you're specifying all of the column values in the correct order, then use this:
psmt=con.prepareStatement("Insert into TR_LogTime values((Select count(*) from Tr_LogTime) + 1 ,(select sysdate from dual), ?, ?, ?, ?,(select to_date(?,'dd/mm/yyyy')from dual) ,?,?,?,?,?)");
Otherwise, if you're only specifying a subset of the columns, use the syntax of
insert into TR_LogTime (col1, col2, col3, ...) values (?, ?, ?, ...)
(I didn't specify the exact column names in your example since I don't know all of them)
More on this syntax.
try this:
Insert into TR_LogTime (XXX, YYY, Prj_Id, Area_id, Activity_Id, ID_No, Work_Date, Work_Hours, Division, Description, Remarks, Work_Week) values (
(Select count(*) from Tr_LogTime) + 1 , (select sysdate from dual) , ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
You'll need to replace XXX and YYY with the appropriate column names