Hello. I want to execute an insert command when the result of previously select statement is true.
Can i use both data source and result set in my method so i can check if the result is null or not.
Or is there a way to see if ds is null?
Hello. I want to execute an insert command when the result of previously select statement is true.
Can i use both data source and result set in my method so i can check if the result is null or not.
Or is there a way to see if ds is null?
Short answer: yes — you can obtain a Connection from your DataSource, run a SELECT and test whether the query returned rows, then perform an INSERT. That said, treat the DataSource and the ResultSet as different things: the DataSource is a connection factory (usually provided by your container or pool), while the ResultSet is the query cursor returned by executing SQL. ‘s suggestion to check whether the SELECT produced a row is correct, and is right that the approach will work — but there are important practical details and safer alternatives.
If your ds variable is null, that usually means the JNDI/resource wiring or injection failed. Troubleshoot by verifying the JNDI name in your server config (context.xml / web.xml / server.xml), checking startup logs for naming exceptions, and failing fast in initialization so the problem is obvious rather than hidden at runtime.
Avoid the classic “select-then-insert” race condition in concurrent environments. Prefer one of these patterns:
INSERT INTO my_table (id, col)
SELECT ?, ?
WHERE NOT EXISTS (SELECT 1 FROM my_table WHERE id = ?); INSERT INTO my_table (id, col) VALUES (?, ?)
ON CONFLICT (id) DO NOTHING; Example Java flow (using your DataSource and a PreparedStatement):
String sql = /* conditional-insert SQL above or DB-specific upsert */;
try (Connection c = ds.getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, id);
ps.setString(2, value);
ps.setInt(3, id); // if SQL needs a third param
int rows = ps.executeUpdate();
// rows>0 => inserted; rows==0 => already existed
} Use parameterized statements, try-with-resources, and proper transaction/isolation settings if you must do separate SELECT and INSERT. Database-side checks (atomic SQL or unique constraints) are usually the cleanest, most robust choice.
You can check is the resultset you execute has any records,
if(resultset.next()) or other methods can be used for this purpose.
Yes, you are on right way.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.