I was trying to delete a column in a SQLite database table using JDBC. As there is no such function in SQLite, to achieve this, I used this approach:
Create a new table (t1_backup) with all columns but not the one to be deleted,
Copy all data (except that of the column to be deleted) to the new table,
Drop the old table (t1),
Rename the new table (t1_backup --> t1).
The actual code is as follows:
Connection cn = DriverManager.getConnection("jdbc:sqlite:"+path);
Statement stmt = new Statement();
stmt = cn.createConnection();
stmt.execute("CREATE TABLE t1_backup(id);");
stmt.executeUpdate("INSERT INTO t1_backup SELECT id FROM t1;");
stmt.execute("DROP TABLE t1;");
stmt.execute("ALTER TABLE t1_backup RENAME TO t1;");
The first two statements were executed without a problem. But when the DROP TABLE statement was executed, it gave me java.sql.SQLException: [SQLITE_LOCKED] A table in the database is locked (database table is locked).
I have found a solution but I was not sure why it worked. The solution is to create three more Statement objects, connect them to the same database and execute each of the four SQL statements with a different Statement object:
stmt.execute("CREATE ...");
stmt2.executeUpdate("INSERT ...");
stmt3.execute("DROP ...");
stmt4.execute("ALTER ...");
Can this be explained?
The JDBC I am using is the one by Xerial.
Thank you.
Related
I have a JDBC code which retrieves data from database and get queries at runtime. At runtime, it will go to database and will try to get data and write it to a file. If table is not present it gives exception that table not found. How to handle this?
Here I can not use,
ResultSet rs = md.getTable()
I have to check at runtime only.
SQL Example : select * from table; Preparedstatement and ResultSet here,
At runtime this table variable will get names of table when loop above this will iterate. If table is not there then it gives this exception on console.
How to handle this smoothly?
If you dont want that exception, first you should check what tables are there in the database. If the table doesn't exist you can create and avoid that exception.
DatabaseMetaData dbm = con.getMetaData();
ResultSet tables = dbm.getTables(null, null, "your_table_name", null);
if (tables.next()) {
// Table exists
}
else {
// Table does not exist
}
if the table doesnot exist, you may need to create a new table to avoid such exception later.
with hsqlDB you can do a CREATE TABLE IF NOT EXISTS newTable (column details...) if you only wanted to be sure before creating a new one.
I need a java application that can export some data from a Oracle database and write it to a Excel file everyday. I am really new to JAVA so I am making this app step by step.
First to all I'm going to show the database schema (simplified version):
GLOBAL (allocated in bar.domain.es)
-DATABASE1:
TABLE A
TABLE B
TABLE C
-DATABASE2:
TABLE 1
TABLE 2
One part of my code is:
//Loading the driver
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("Driver Loaded");
//Connecting to Oracle Database
java.sql.Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
System.out.println("Connection Success");
//Creating statement
Statement stat = con.createStatement();
//Creating the query string
String query ="SELECT count(*) FROM TABLE2 WHERE DATE=150603 AND ID=238";
// Creating the statement to execute the Query
ResultSet rs = stat.executeQuery(query);
where DBURL is: "jdbc:oracle:thin:#bar.domain.es:1521:XE"
With this code I get the message Connection Success so my app is connected to the database schema. However, in this schema there are several databases with several tables on each so my problem comes when I try to launch the query. The program doesn't find TABLE2 which is a table of the DATABASE2. I think that I should specify in someway that I want to search this TABLE2 in DATABASE2 but I don't know how.
You can specify in the query what database the table is in
String query ="SELECT count(*) FROM DATABASE2.TABLE2 WHERE DATE=150603 AND ID=238";
We have multiple tables and all are related with first table's primary key (example: id). Id is configured as a sequence and while inserting data into to first table we are using sequence.nextval in the insert query.
Now while inserting data to other tables, how to get current sequence value or current Id.
We have tried below options:
sequence.currval, directly in the insert statement
2.select sequence.currval from dual
Above two options throwing error while using getJdbcTemplate().update().
Could anyone please suggest how to get current sequence value to pass to other tables after inserting data into first table??
If you want to insert the same id (which comes from a sequence) to different tables, simple get it form the first insert and use it in the other inserts.
PrepearedStatement stmt1 = conn.prepareStatement("INSERT INTO TABLE1 (id) VALUES(yoursequence.nextval)", Statemet.RETURN_GENERATED_KEYS);
stmt1.executeUpdate();
ResultSet rs = stmt1.getGeneratedKeys();
rs.next();
long id = rs.getLong(1);
PrepearedStatement stmt2 = conn.prepareStatement("INSERT INTO TABLE2 (id) VALUES(?)");
stmt2.setLong(1,id);
stmt2.executeUpdate();
I need to delete all the rows in an Apache Derby database in Java.
If I execute statement.executeUpdate("DELETE FROM TABLENAME WHERE CONDITION=") it works, but if I try statement.executeUpdate("DELETE FROM TABLENAME") it does not delete all the rows. I tried TRUNCATE and it does not work either.
Any ideas.
Use dummy condition to delete all the records :
DELETE FROM TABLENAME WHERE 1=1;
I want to delete the current row displayed in jframe from the table contact
I wrote the code
try
{
conn = java.sql.DriverManager.getConnection(connectionURL, "usrnme", "pswd");
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);//also tried with ResultSet.TYPE_SCROLL_SENSITIVE
rs.deleteRow();
rs.next();//it may or may not include in code
}
catch(Exception e){System.out.println( "JDBC error: " + e );}
sql query
String sql="SELECT * FROM contact order by first_name, last_name";
rs=stmnt.executeQuery(sql);
but it throws an exception while running
JDBC error: java.sql.SQLException: 'deleteRow' not allowed because the ResultSet is not an updatable ResultSet.
Help me!
I suggest to do it totally in SQL, where you need to additionally select the (internal) rowid of every row
SELECT c.*, c.rowid FROM contact c ORDER BY first_name, last_name
and afterward delete a row by it row id
DELETE FROM contact c WHERE c.rowid = (?)
this works for Oracle, but every Databasetype does use internal rowid's. For MYSQl you get the rowid by using #rowid as far as I remember
Instead of ResultSet.TYPE_SCROLL_INSENSITIVE, try ResultSet.TYPE_SCROLL_SENSITIVE. That might do the trick. If that doesn't work, try an SQL DELETE statement (w3schools.com) instead to delete the row.
Edit: Now that I reread your code: you need to move to the next row before you call deleteRow. Opening a statement sets the cursor before the first row. If your call to next returns true, your cursor points to the first row. Only if the cursor points to a valid row can you delete the row. HTH.
To make use of updatable ResultSet , your table must contain primary key column. It is the link between data present in ResultSet and DB. Since I infer from your comments your table does not contain primary key, you can delete row using sql query.
String sql = "DELETE FROM contact WHERE first_name='test'";
stmt.executeUpdate(sql);