How to get the record deletion date in SQL? - java

I need to delete the a specific student from stdnt table and insert that students data into a new table stdnt_log including the 'leaving_date' field, which would be the record's deletion date
sql = "INSERT INTO stdnt_log SELECT rollno, name, grade, leaving_date FROM stdnt WHERE rollno = ?";
sql = "DELETE FROM stdnt WHERE rollno = ?";

Simpler option - if you can/want to apply it - is to alter the stdnt table and add another column: deactivation_date:
alter table stdnt add deactivation_date date;
Once someone gets deactivated, just update that column:
update stdnt set
deactivation_date = sysdate
where student_id = some_value;
Active students would then be
select * from stdnt where deactivation_date is null;
Simpler to implement, easier to maintain. Drawback? Table will be larger and larger, but hey, this is Oracle, it handles zillions of rows without problems.

Related

Inserting value in middle table in sqlite

I am trying to insert a value in a middle table, which is created by having two other tables relationship many to many. So this middle table has 2 foreign keys(idProduct and idWarehouse), one for each table and an additional row(storage). So I have trouble inserting in this third row.
It gives this error:
Result: near "SELECT": syntax error
At line 1:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT
This is my code:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT id FROM Products
WHERE nameProduct = 'cheese',
SELECT id FROM Warehouse
WHERE nameWarehouse = 'Vegas',
'10')
Each of the queries must be enclosed inside parantheses:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) VALUES
(
(SELECT id FROM Products WHERE nameProduct = 'cheese'),
(SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
'10'
);
This will work if theses queries return always only 1 row, so both columns nameProduct and nameWarehouse must be unique.
The statement can also be written without the VALUES clause, with SELECT:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
SELECT
(SELECT id FROM Products WHERE nameProduct = 'cheese'),
(SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
'10';

ANDROID STUDIO / SQLiteLog: (1) near "LIMIT": syntax error

I am trying to delete the duplicates that I am getting in my database using DELETE function of my SQL with LIMIT 1 but it is showing me the "LIMIT" syntax error .
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS users (name VARCHAR , age INT(3))");
myDatabase.execSQL("INSERT INTO users (name, age) VALUES ('Vaishant', 21)");
myDatabase.execSQL("INSERT INTO users (name, age) VALUES ('Tommy',4)");
myDatabase.execSQL("DELETE FROM users WHERE name = 'Vaishant' LIMIT 1");
Can someone tell me why I am getting this error and how to correct it ?
SQLite does not support LIMIT in a DELETE statement.
Use a subquery that returns the rowid of a row that contains the name that you search for:
String sql = "DELETE FROM users WHERE rowid = (SELECT rowid FROM users WHERE name = 'Vaishant' LIMIT 1)";
myDatabase.execSQL(sql);
If you want to delete the duplicate names and keep only 1, then you can do this:
DELETE FROM users
WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.name = users.name AND u.rowid < users.rowid)
or:
DELETE FROM users
WHERE rowid NOT IN (SELECT MIN(rowid) FROM users GROUP BY name)
In your delete statement you are using limit with Delete query. You should use it as below:
First add id column as primary key in your table
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS users (ID INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR , age INT(3))");
change the query of delete as below
myDatabase.execSQL("DELETE FROM users
WHERE id IN
(SELECT id FROM
(SELECT id,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) AS row_num FROM users )t
WHERE row_num > 1)");

update statement with dynamically changing rows using prepared statement

I am planning to execute an update statement using a prepared statement that makes use of a dynamically changing number of columns. for eg: in the first update statement I update only name and age of a table. in the second instance, I update age, city, state, country..etc. in the next instance, I update 150 columns like this.
can someone provide me what is the perfect approach for this in java?
following is the example
If the user provides input for name and age then I update
UPDATE table1 set name = <> ,age = <>;
If the user provides input for city name state country and pin then the update statement should be like this-
UPDATE table1 set name = <>, city = <>,state= <>,country=<>, pin = <>;
Build your sql query like this
update demotable set col1 = case when #col1 is null then col1 else #col1 end
OR
Here #col is passed as value from front end.
from which you may create dynamic sql
declare #col1 nvarchar(max) /// from front you can pass your column value with its column name like: col1 = 'col1'
declare #Query = 'update demotable set = ' + #col1 /// it create query as update demotable set col1 = 'col1'
PREPARE stmt1 FROM #Query ;
EXECUTE stmt1
DEALLOCATE PREPARE stmt1;
I am new to MYSQL but this logic will surely work.
You can write one statement like this:
UPDATE table1
SET name = COALESCE(?, name),
age = COALESCE(?, age),
city = COALESCE(?, city),
. . .
Notes:
This assumes that the values are not being set to NULL.
The ? is a placeholder for a parameter. Don't munge query strings with user input.
Presumably you want a WHERE clause to limit what rows get updated.

PostgreSQL: Update my user table via Java

In PostgreSQL user is a reserved keyword that is used in an internal table, however I also have a separate user table in my own database that I need to use. Whenever I try to execute INSERT or UPDATE statements on the table, it generates the following error: The column name 'id' was not found in this ResultSet.
This is the Java code I am currently using:
PreparedStatement stat1 = conn.prepareStatement("SELECT id FROM user;");
PreparedStatement stat2 = conn.prepareStatement("UPDATE user SET date_created = ? , last_updated = ? , uuid = ? WHERE id = ?;");
ResultSet rs = stat1.executeQuery();
while(rs.next()){
UUID uuid = UUID.randomUUID();
String tempId = uuid.toString();
stat2.setTimestamp(1, curDate);
stat2.setTimestamp(2, curDate);
stat2.setString(3, tempId);
stat2.setLong(4,rs.getLong("id"));
stat2.executeUpdate();
}
So my question is, how could I insert or update the values in my personal user table without interfering with the keyword restriction?
Use this:
prepareStatement("UPDATE \"user\" set date_created = ?")
Or, better yet, rename your user table to something else, like users:
ALTER TABLE "user" RENAME TO users;
Escape the table name like this
select * from "user";

How to insert record in many to many relationship link table

Current I am working on a hospital management system project. I have two tables doctor and patient and have made a link table Visits between them. Primary Keys of doctor and patient tables respectively are foreign keys of the Visits table. I am able to update the doctors table from my code. Whenever a record is inserted into the patients table, the doctor table is checked to find out whether the allocated doctor exists or not, if doctor exists and insertion is made into the visits table. For this I have created a trigger on Patients Table. Now whenever I try to register patients, the patients table gets updated but the code throws a MySQLException with message "Column Count Does Not Match Value Count At Row 1".
Code
this.stmt=this.mycon.createStatement();
String query_add_patient="insert into patients values ('"+nic+"','"+name+"','"+address+"','"+city+"',"+age+",'"+dob+"','"+telephone+"');";
String query_select_employees="select * from employees where employee_type='Doctor' and employee_qualification='"+doctor+"'";
ResultSet rs=this.stmt.executeQuery(query_select_employees);
if(!rs.next()) {
JOptionPane.showMessageDialog(this, "This Doctor is not available in this facility!!!","Admin Error",JOptionPane.ERROR_MESSAGE);
return false;
}
rs.first();
String pattern = "yyyy-m-d";
SimpleDateFormat format = new SimpleDateFormat(pattern);
String enic=rs.getString("employee_nic");
System.out.println(enic);
String query="insert into Visits (patient_nic,employee_nic) values ("+nic+","+enic+")";
this.stmt.executeUpdate(query_add_patient);
closeConnection();
openConnection();
this.stmt=mycon.createStatement();
this.stmt.executeUpdate(query);
return true;
Here the statement "insert into visits" causes the problem. I tried to close and open the connection again but that did not work. The structure for my visits table is
Visits
patient_nic (varchar(45)) FK --> patient.patient_nic
employee_nic (varchar(45)) FK --> employee-->employee_nic
Make Sure the Column Names Each Have a Matching Value and Vice Versa.
E.g
Good
$query = "INSERT INTO table (first_name, last_name)
VALUES(Mr,Kyaw)";
Bad
$query = "INSERT INTO table (first_name, last_name)
VALUES(Mr,Kyaw,Thu)"; //can give Column Count Does Not Match Value Count At Row 1 exception

Categories

Resources