How to getGenerated id from parent table and insert into child table - java

try {
currentCon = ConnectionManager.getConnection();
psParent=currentCon.prepareStatement("insert into accommodation (type,name,price,description,username)values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
psParent.setString(1,type);
psParent.setString(2,name);
psParent.setFloat(3,price);
psParent.setString(4,username);
psParent.executeUpdate();
accid= 0;
rs = psParent.getGeneratedKeys();
if (rs.next())
accid = rs.getInt(1);
rs.close();
psParent.close();
psChild=currentCon.prepareStatement("insert into room (accid, bed)values(?,?)");
psChild.setInt(1,accid);
psParent.setString(2,bed);
psChild.executeUpdate(); }
after I run this, I got this error message : failed: An Exception has occurred! java.sql.SQLRecoverableException: internal error
Is there's something wrong with the code? Thank you for your help

Your usage of getGenereatedKeys() actually looks correct to me for Oracle, but the problem is actually with your first insert statement. You have placeholders (and column names) for 5 columns, but you only bind 4 values. Try something like this:
String sql = "insert into accommodation (type, name, price, description, username) ";
sql += "VALUES (?, ?, ?, ?, ?)";
String generatedColumns[] = { "ID" };
psParent = currentCon.prepareStatement(sql, generatedColumns);
psParent.setString(1, type);
psParent.setString(2, name);
psParent.setFloat(3, price);
psParent.setString(4, description); // I ADDED THIS LINE
psParent.setString(5, username);
psParent.executeUpdate();
I am assuming that you have a variable containing a description to be inserted. If not, then remove description and its placeholder from the prepared statement entirely, or just insert null.

Related

Prepared statement and serial data type

This is my PostgreSQL code:
CREATE TABLE "user" (
id serial UNIQUE,
username varchar,
password varchar,
email varchar,
);
I want to create Java method, which adds new user to my table user:
public static void addUser(Connection con) throws SQLException {
String sql = "INSERT INTO user VALUES (?, ?, ?)";
try(PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, "test");
ps.setString(2, "test");
ps.setString(3, "test#email.com");
ps.executeUpdate();
}
}
}
Because column id is serial, I don't create prepared statement for this column (even without java, I would make insert only with remaining values, since id would be generated automatically). Hovewer, when I run this code, I get the following error:
ERROR: column "id" is of type integer but expression is of type character varying
What am I doing wrong?
Always specify the target columns in an INSERT statement. And as user is a reserved keyword, you have to quote it (but it would be better if you found a different name)
String sql = "INSERT INTO \"user\" (username, password, email) VALUES (?, ?, ?)";

Java JDBC Error Insert into

Here is the code:
String sqlstatment = "INSERT INTO order (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
ResultSet keys = null;
try (
PreparedStatement stmt = conn.prepareStatement(sqlstatment, Statement.RETURN_GENERATED_KEYS);
){
stmt.setInt(1, 1);
stmt.setInt(2, 3);
stmt.setInt(3, 5);
int affected = stmt.executeUpdate();
if (affected == 1){
keys = stmt.getGeneratedKeys();
keys.next();
int newKey = keys.getInt(1);
orderBean.setOrderID(newKey);
}else{
System.out.println("An Error has ocurred while creating the Order.");
}
}catch (SQLException e){
System.err.println(e.getMessage());
}finally{
if (keys != null) keys.close();
}
And when I run the code I get this error:
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 'order (orderedBy, totalItems, totalPrice) VALUES (1, 3, 5)' at line 1
I'm not entirely sure why I get the error so if you know that would be great.
order is a reserved word, try
String sqlstatment = "INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) "+
"VALUES (?, ?, ?);";
Your query contains a RESERVED KEYWORD order as your table name. MySQL documentation clearly suggests that use of such keywords should always be avoided, if they need to be used then it has to be with the use of backticks as shown below '`'.
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
Your query that gets assigned to a String in turn should be changed to the following to resolve this error!
"INSERT INTO \"order\" (orderedBy, totalItems, totalPrice) VALUES (?, ?, ?);"
The following is a documentation link to the reserved keywords for MySQL -> Documentation
Hope this helps!

How to write "INSERT IF EXISTS UPDATE" in Oracle using JAVA

I have a ERROR_MSG table which stores error messages with some ids. I want to insert error message if id is not present in table and if its present update error message. Inserting using below java JDBC code.
ID ERROR_MSG
1 ERR1
2 ERR2
3 ERR3
This is my code:
insertQry = "SQL";
Connection con = null;
PreparedStatement stmt = null;
try {
con = getDataSource().getConnection();
stmt = con.prepareStatement(insertQry);
for(ListingAckNackData errorList: listOfListingERROR) {
stmt.setLong(1, eqGlobalData.getSrcMsgId());
stmt.setString(2, errorList.getGliId());
if (null != errorList.getListingRevisionNo()) {
stmt.setInt(3, errorList.getListingRevisionNo());
} else {
stmt.setNull(3, Types.NULL);
}
if (null != errorList.getErrorMessage()) {
stmt.setString(4, errorList.getErrorMessage());
} else {
stmt.setNull(4, Types.NULL);
}
stmt.addBatch();
}
stmt.executeBatch();
}
The simplest solution in JAVA is to check if the row exist.
You start by getting a row count for the specific id you want to insert/update
select count('a') as rowExist from table where id = ?
Then, based on the result, you can easily create your query
if(rowExist > 0){
query = "update ..";
else
query = "insert ...";
Note that the parameters are probably not in the same order as you expect, you need to create the insert in the correct order to have the id at the end (since update need a where clause)
insert into Table (name, birthday, id) values (?, ?, ?)
update Table set name = ?, birthday = ? where id = ?
It is possible to run a database statement as questioned. Simply use SQL command MERGE INTO... IF NOT MATCHED INSERT... IF MATCHED UPDATE ...
You will find an full example and documentation here.

Insert database mysql get issue

i got issue when i go to Insert value to DB (do nothing).
before that i do select table to get last id, and it worked.
Here's my Code:
IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
Connection connection = null;
int idRoom = params.getInt("idRoom");
String betsmall = params.getUtfString("betsmall");
int Uid = params.getInt("recid");
try{
connection = dbManager.getConnection();
PreparedStatement stmt = connection.prepareStatement("SELECT id_game from detail_game ORDER BY id_game DESC LIMIT 1");
ResultSet res = stmt.executeQuery();
if (!res.first())
{
trace("bla bla");
}
int id = res.getInt("id_game");
trace (id);
// **till here there is no problem, i can get id from select query
PreparedStatement stmts = connection.prepareStatement("INSERT INTO detil_bet (id_user, id_room, id_bet, bettype) VALUES (?, ?, ?, ? ");
stmts.setInt(1, Uid);
stmts.setInt(2, idRoom);
stmts.setInt(3, id);
stmts.setString(4, betsmall);
stmts.executeUpdate();
}
}
Here's the problem, insert do nothing.
PreparedStatement stmts = connection.prepareStatement("INSERT INTO detil_bet (id_user, id_room, id_bet, bettype) VALUES (?, ?, ?, ? ");
Looks like you need some end parentheses in "VALUES".
A catch block to print stack trace would have told you the issue here as well. I'm not the best SQL guy, I always use this to check my SQL syntax as well to double check if I've done everything right.
your connection seems not auto commit. Try to add
stmts.commit();
after "stmts.executeUpdate();".

Insert new data into specific table in a the database

I design a system and I want from the user firstly to choose from a combo box the name of the table he want to insert then he will enter the rest of the fields.. My question is that how can I let the user enter the name of the table using sql statement .. I write the following doesn't but it doesn't work ??
try {
Object service = Service_ComboBox.getSelectedItem();
String ref = "0";
String title = title_TextField1.getText();
Object riskRating = riskRating_ComboBox3.getSelectedItem();
Object rootCause = rootCause_ComboBox4.getSelectedItem();
Object impact = impact_ComboBox1.getSelectedItem();
Object likelihood = likelihood_ComboBox2.getSelectedItem();
String efforts = efforts_TextField7.getText();
String finding = finding_TextField9.getText();
String implication = implication_TextArea1.getText();
String recommendation = recommendation_TextArea2.getText();
Connection conn= DriverManager.getConnection ("jdbc:oracle:thin:#localhost:1521:XE","SYSTEM","*******");
String query = "insert into ? (Service,Ref,Title,Risk_Rating,Root_cause,Impact ,Likelihood,Efforts,Finding,Implication,Recommendation)values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? , ?)";
PreparedStatement myStatment = conn.prepareStatement(query);
myStatment.clearParameters();
myStatment.setString(1, service.toString());
myStatment.setString(2, service.toString());
myStatment.setString(3, ref);
myStatment.setString(4, title);
myStatment.setString(5, riskRating.toString());
myStatment.setString(6, rootCause.toString());
myStatment.setString(7, impact.toString());
myStatment.setString(8, likelihood.toString());
myStatment.setString(9, efforts);
myStatment.setString(10, finding);
myStatment.setString(11, implication);
myStatment.setString(12, recommendation);
boolean myResult = myStatment.execute();
System.out.println("done");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Information is missing or incorrect! Please Make sure to enter correct information");
Logger.getLogger(Insert_info.class.getName()).log(Level.SEVERE, null, ex);
return;
}
JOptionPane.showMessageDialog(this, "Your information was saved successfully!");
insert into ?
You cannot use a bind variable for schema object names. The reason being that when you prepare the statement, the database needs to know what tables are involved, and decide which indexes to use, so the query SQL needs to be known (only the data can change).
So if you want to do this, you have to use string interpolation to construct the query (only for the table name, continue to use bind variables for the data!).
String query = "insert into "+ tableName + ....
Make sure that you validate this tableName. In your case, it can probably be checked against a HashSet of valid table names. Do not let this become an SQL injection problem.
Use the folowing sintax:
String query = "insert into " &tablename "bla bla predicates"
To avoid the sql injection create roles in your databases and give access to the tables you want to be used by your visitors/users.
Or you can use a wildcard :
Create a Variable tbl_name
String query = "insert into "(select table_name from user_tables where table_name like '%tbl_name%')"<br/>
- next create a decision "IF" and throw the output of the wildcard in it.If it matches the tables you have then ok if not treat it with an error message.

Categories