check if row already exists if does not exist insert row otherwise show message - java

String sql2="if not exists(select * FROM stock where productCode=?)\n" +
"Begin\n" +
"insert into stock "
+ "(productName,quantity,currentQuantity,price,companyName,categoryName,productCode) "
+ "values(?,?,?,?,?,?,?)\n" +
"End";
PreparedStatement pst2 = con.prepareStatement(sql2);
pst2.setString(1,productCodeTextField.getText());
pst2.setString(2,productNameTextField.getText());
pst2.setString(3,quantityTextField.getText());
pst2.setString(4,quantityTextField.getText());
pst2.setString(5,priceTextField.getText());
pst2.setString(6, (String) companyNameJComboBox.getSelectedItem());
pst2.setString(7, (String) categoryNameJComboBox.getSelectedItem());
pst2.setString(8,productCodeTextField.getText());
int x=pst2.executeUpdate();
if(x!=0){
productCodeTextField.setText("");
productNameTextField.setText("");
quantityTextField.setText("");
priceTextField.setText("");
JOptionPane.showMessageDialog(null,"Product entered");
}else{
JOptionPane.showMessageDialog(null,"Product already exists");
}
I am successfully able to check for for already existing products before insertion but i am not able to populate the correct message on the basis of the query executed. The executeUpdate is always returning some value even when the insertion is not being done. How to fix this.

There is an easier solution that may work for you:
Throw away the first query that checks whether the entry already exists
Rewrite sql2 as follows:
INSERT INTO stock
(productCode, productName, quantity, price, companyName, categoryName)
VALUES (?,?,?,?,?,?)
WHERE NOT EXISTS
(SELECT * FROM stock WHERE productCode = ?)
Add: pst.setString(7, productCodeTextField.getText());
executeUpdate() returns an int indicating the number of rows affected by the query. Use this variable to determine if a row was added. If the variable != 0 display success message.

INSERT INTO stock
(productCode, productName, quantity, price, companyName, categoryName)
select ?,?,?,?,?,?
WHERE NOT EXISTS
(SELECT * FROM stock WHERE productCode = ?)
This is how it works for SQL Server. 3 and 4 points same as Coop answered

Related

Return array of deleted elements postgresql JDBC

This is my database:
dragons
id, key, name, age, creation_date
users
id, name, user, pass
users_dragons
user_id, dragon_id
So this is my code for deleting dragons from the database that have a bigger key that the passed and belongs to a determination user. The SQL query works perfectly for deleting them but not for returning the array of keys from the deleted elements.
I tried using PreparedStatement but later I checked, as far as I know, that this class doesn't return arrays, and the CallableStatement is only for executing processes in the db, and I don't know how they return arrays.
String query = "" +
"DELETE FROM dragons " +
"WHERE id IN (SELECT d.id FROM dragons d, users u, users_dragons ud" +
" WHERE d.key > ?" +
" AND ud.dragon_id = d.iD" +
" AND ud.user_id in (select id from users where id = ?)) RETURNING key INTO ?";
CallableStatement callableStatement = connection.prepareCall(query);
int pointer = 0;
callableStatement.setInt(++pointer, key);
callableStatement.setInt(++pointer, credentials.id);
callableStatement.registerOutParameter(++pointer, Types.INTEGER);
callableStatement.executeUpdate();
return (int []) callableStatement.getArray(1).getArray();
The code is giving me the error, but is obvious because the CallableStatement needs a postgres function to run and not a simple SQL query
org.postgresql.util.PSQLException: This statement does not declare an OUT parameter.
Use { ?= call ... } to declare one.
at org.postgresql.jdbc.PgCallableStatement.registerOutParameter
.......
It would be really helpful how would be the correct JDBC algorithm to delete the elements from the database and return the array of keys of the deleted items.
You treat such a statement like a normal SELECT statement: use java.sql.PreparedStatement.executeQuery() or java.sql.Statement.executeQuery(String sql) to execute the statement and get a result set.
java.sql.CallableStatement is for calling Procedures (but you don't need it in PostgreSQL).

Merging two SQL statement in one , to update a row in a table if it meet certain conditions

I am working on an app using JDBC to update stocks and place order.
I am storing the products and I want to update the products if the quantity requested is less then the stored one , and I want to delete the product from the database if the quantity is equal to the number of current stock in the DB.
I am using two different statements, but I would like to use just one of them. For example, if I want to add an order into the DB the things that are going to be requested by the system are a name and product quantity. The product quantity would get subtracted from the total quanitity of the product on the DB. The pseudocode would be
IF product quantity - user quantity =0 THEN DELETE product FROM database
ELSE UPDATE product quantity TO product quantity-user quantity ON THE database
product quantity=quantity of the product in the database
user quantity=quantity requested by the user
The Prepared Statements that I have for now are these two
UPDATE products SET quantity=quantity-? WHERE product_name=?
DELETE FROM products WHERE product_name=?
I would like to merge them as one if possible
In a production system you would do this sort of thing.
For an order, as you said, do this.
UPDATE products SET quantity=quantity-? WHERE product_name=?
Then, in an overnight or weekly cleanup do this to get rid of rows with no quantity left.
DELETE FROM products WHERE quantity = 0
When you want to know what products are actually available, you do
SELECT product_name, quantity FROM products WHERE quantity > 0
The concept here: rows with zero quantity are "invisible" even if they aren't deleted.
If this were my system, I would not DELETE rows. For one thing, what happens when you get more products in stock?
One way is to loosen security by setting the MySQL Configuration Property allowMultiQueries to true in the connection URL.
Then you can execute two SQL statements together:
String sql = "UPDATE products" +
" SET quantity = quantity - ?" +
" WHERE product_name = ?" +
" AND quantity >= ?" +
";" +
"DELETE FROM products" +
" WHERE product_name = ?" +
" AND quantity = 0";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, userQuantity);
stmt.setString(2, productName);
stmt.setInt(3, userQuantity);
stmt.setString(4, productName);
stmt.execute();
int updateCount = stmt.getUpdateCount();
if (updateCount == 0)
throw new IllegalStateException("Product not available: " + productName);
// if you need to know if product got sold out, do the following
stmt.getMoreResults();
int deleteCount = stmt.getUpdateCount();
boolean soldOut = (deleteCount != 0);
}

Values Not Being Inserted with prepareStatement in Derby Database

I've created a very simple table, and am attempting to insert into it. The table exists, but nothing I try to insert sticks; the resultSet is always null. I think I'm auto-incrementing my primary key correctly. Any ideas? Thank you!
String createGenreTableSQL = "CREATE TABLE Genre (GenreID INTEGER NOT NULL GENERATED ALWAYS " +
"AS IDENTITY (START WITH 1, INCREMENT BY 1), genreName varchar(60))";
statement.executeUpdate(createGenreTableSQL);
String prepGenreInsert = "INSERT INTO Genre(genreName) VALUES (?)";
psInsert = conn.prepareStatement(prepGenreInsert);
allStatements.add(psInsert);
psInsert.setString(1,"Television");
psInsert.setString(1,"Movies");
psInsert.setString(1,"VideoGames");
psInsert.setString(1,"Animes");
String fetchAllDataSQL = "SELECT * from Genre";
resultSet = statement.executeQuery(fetchAllDataSQL);
while (resultSet.next()) { //resultSet shows null
int genreID = resultSet.getInt("genreID");
String genreName = resultSet.getString("genreName");
System.out.println("GenreID:" + genreID + " Name: " + genreName);
}
The setString method simply binds the given value to the given parameter index. It does not actually execute the query. I believe what you want to do is
psInsert.setString(1,"Television");
psInsert.execute();
psInsert.setString(1,"Movies");
psInsert.execute();
psInsert.setString(1,"VideoGames");
psInsert.execute();
psInsert.setString(1,"Animes");
psInsert.execute();

one Field for 2 parameters in JAVA

public ArrayList searchCustomer(String cid) throws SQLException {
ArrayList searchCustList = new ArrayList();
PreparedStatement pStmt = connection.prepareStatement("select * from customer where (custID = ? OR firstName LIKE ?)");
pStmt.setString(1, cid);
pStmt.setString(2, "%" + cid + "%");
please explain last command i used one text field for search customer by name or ID can any body explain last line
Your question is unclear, but if you want to understand :pStmt.setString(2, "%" + cid + "%");
Then it set the second parameter in sql query to the value of cid variable, and add % around
Adding % around, mean in an SQL Like 'any character', so having %cid% mean anything containing cid in it.
As the actual query use cid for either custId or firstName, it mean that it look for user having a specific id, or having in its firstname the id.
Which is strange, and looks like more a bug, than a logical query, but maybe it come from old legacy having some id in firstname, who knows

SQL INSERT with loop with multiple rows

I'm trying to insert skeleton data into a database using jdbc.
So far my code is:
Statement st=con.createStatement();
String sql = "INSERT INTO student (studentid, titleid, forename, familyname, dateofbirth) "
+ "VALUES (1, 1, 'forename1', 'surname1', '1996-06-03');";
I need to create 100 entries for this and I'm not too sure how to go about doing it.
All I want is the student id, titleid, forename and familyname to increment by 1 until it reaches 100 entries with those rows filled in, date of birth doesn't need to be altered. I'm asking how to do a loop for this
General answer - You should use PrepareStatement instead of Statement and execute as batch.
Common way to insert multiple entry or execute
String sql = "INSERT INTO student (studentid, titleid, forename, familyname, dateofbirth) "
+ "VALUES (?, ?, ?, ?, ?);";
ps = connection.prepareStatement(SQL_INSERT);
for (int i = 0; i < entities.size(); i++) {
ps.setString(1, entity.get...());
...
ps.addBatch();
}
ps.executeBatch();
Important Note:
Why you should use PrepareStatement Over Statement
SQL Injection Example
There are two ways to do this. You can put your insert query inside a loop or you can put your loop inside an insert query. I have found that the better method depends on the database engine (but I've never used postresql) and the number of records you want to insert. You could bump up against the maximun query length or number of parameters or something.
The following code sample is ColdFusion, but it is intended to show the general idea of having a loop inside a query. You would have to write equivalent code in java.
<cfquery>
insert into yourtable
(field1
, field2
, etc)
select null
, null
, null
from SomeSmalllTable
where 1 = 2
<cfloop>
union
select <cfqueryparam value="#ValueForField1#">
, <cfqueryparam value="#ValueForField#">
, etc
</cfloop>
</cfquery>

Categories

Resources