How to Truncate All Tables in Sqlite Database using Java?
I know i can do this
{
...
String table_name1 = "Delete From table_name1";
String table_name2 = "Delete From table_name2";
String table_name3 = "Delete From table_name3";
String table_name4 = "Delete From table_name4";
String table_name5 = "Delete From table_name5";
stmt.executeUpdate(table_name1);
...
}
I can execute all these Strings to do the task but it increases the Lines of Code.
Is there a way to Truncate all tables in a Database with a single command, without separately typing there names?
There's no TRUNCATE in sqlite. You can use DELETE FROM <tablename> to delete all table contents. You'll need to do that separately for each table.
However, if you're interested in removing all data, consider just deleting the database file and creating a new one.
SQLite do not have TRUNCATE TABLE command in SQLite but you can use SQLite DELETE command to delete complete data from an existing table, though it is recommended to use DROP TABLE command to drop complete table and re-create it once again.
Try
{
...
String table_name1 = "DELETE FROM table_name1";
String table_name2 = "DELETE FROM table_name2";
String table_name3 = "DELETE FROM table_name3";
String table_name4 = "DELETE FROM table_name4";
String table_name5 = "DELETE FROM table_name5";
stmt.executeUpdate(table_name1);
...
}
Related
I am trying to use the update query with the LIMIT clause using sqlite-JDBC.
Let's say there are 100 bob's in the table but I only want to update one of the records.
Sample code:
String name1 = "bob";
String name2 = "alice";
String updateSql = "update mytable set user = :name1 " +
"where user is :name2 " +
"limit 1";
try (Connection con = sql2o.open()) {
con.createQuery(updateSql)
.addParameter("bob", name1)
.addParameter("alice", name2)
.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
}
I get an error:
org.sql2o.Sql2oException: Error preparing statement - [SQLITE_ERROR] SQL error or missing database (near "limit": syntax error)
Using
sqlite-jdbc 3.31
sql2o 1.6 (easy database query library)
The flag:
SQLITE_ENABLE_UPDATE_DELETE_LIMIT
needs to be set to get the limit clause to work with the update query.
I know the SELECT method works with the LIMIT clause but I would need 2 queries to do this task; SELECT then UPDATE.
If there is no way to get LIMIT to work with UPDATE then I will just use the slightly more messy method of having a query and sub query to get things to work.
Maybe there is a way to get sqlite-JDBC to use an external sqlite engine outside of the integrated one, which has been compiled with the flag set.
Any help appreciated.
You can try this query instead:
UPDATE mytable SET user = :name1
WHERE ROWID = (SELECT MIN(ROWID)
FROM mytable
WHERE user = :name2);
ROWID is a special column available in all tables (unless you use WITHOUT ROWID)
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.
I am reading a CSV file into my java program and it has an sql query in its every record. I want to parse this (Select)SQL query to find the table names and column names mentioned in those queries.
e.g. Select age,name from Employee
Result:
---- Tables: [Employee]
---- Columns: [age,name]
NOTE: I do not want to fire the queries else I would have used ResultSetMetaData
For simple SQL statements like your example above i would use some simple string methods to get the info. Example:
public static void main (String[]args) {
String sql = "Select age,name,adress,id from Employee where id = 3";
String[] columns = sql.substring(sql.indexOf("Select")+7, sql.indexOf("from")-1).split(",");
String table = sql.substring(sql.indexOf("from")+5).split(" ")[0];
System.out.println(Arrays.toString(columns));
System.out.println(table);
}
I have to do remove the row (containing the userId) in the table "USERS". This is my query:
#SqlUpdate("delete from USERS where userId = :userId ")
void removeUser(#Bind("userId") String userId);
But first I want to remove that user from the table "USERS_DATA" (that is a daughter of USERS) which also contain the "userId". How can I do? I've tried this:
#SqlUpdate("delete from USERS_DATA where userId = :userId " +
" and delete from USERS where userId = :userId")
void removeUser(#Bind("userId") String userId);
but console tell me: java.sql.SQLSyntaxErrorException: ORA-00936: missing expression
Unlike some other RDBMS, Oracle does not allow you to pass two statements in the same SQL command (this helps to prevent SQL injection).
You can try using wrapping both queries in an anonymous PL/SLQ block:
BEGIN
delete from USERS_DATA where userId = :userId;
delete from USERS where userId = :userId;
END;
/
This will allow you to execute both DML statements together as they are part of the singular containing PL/SQL block.
Unfortunately, I am not familiar with that annotation syntax in Java so I cannot help you convert it to Java but I would guess at:
#SqlUpdate("BEGIN " +
"delete from USERS_DATA where userId = :userId; " +
"delete from USERS where userId = :userId; " +
"END;")
void removeUser(#Bind("userId") String userId);
Alternatively, you can create a procedure in Oracle:
CREATE OR REPLACE PROCEDURE delete_user(
in_userID USERS_DATA.USERID%TYPE
)
AS
BEGIN
DELETE FROM USERS_DATA WHERE userId = in_userId;
DELETE FROM USERS WHERE userId = in_userId;
END;
/
And you can then just call this procedure.
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";